target
int64
0
1
func
stringlengths
7
484k
func_no_comments
stringlengths
7
484k
idx
int64
1
368k
1
int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len) { struct inet_sock *inet = inet_sk(sk); struct udp_sock *up = udp_sk(sk); int ulen = len; struct ipcm_cookie ipc; struct rtable *rt = NULL; int free = 0; int connected = 0; __be32 daddr, faddr, saddr; __be16 dport; u8 tos; int err; int corkreq = up->corkflag || msg->msg_flags&MSG_MORE; if (len > 0xFFFF) return -EMSGSIZE; /* * Check the flags. */ if (msg->msg_flags&MSG_OOB) /* Mirror BSD error message compatibility */ return -EOPNOTSUPP; ipc.opt = NULL; if (up->pending) { /* * There are pending frames. * The socket lock must be held while it's corked. */ lock_sock(sk); if (likely(up->pending)) { if (unlikely(up->pending != AF_INET)) { release_sock(sk); return -EINVAL; } goto do_append_data; } release_sock(sk); } ulen += sizeof(struct udphdr); /* * Get and verify the address. */ if (msg->msg_name) { struct sockaddr_in * usin = (struct sockaddr_in*)msg->msg_name; if (msg->msg_namelen < sizeof(*usin)) return -EINVAL; if (usin->sin_family != AF_INET) { if (usin->sin_family != AF_UNSPEC) return -EAFNOSUPPORT; } daddr = usin->sin_addr.s_addr; dport = usin->sin_port; if (dport == 0) return -EINVAL; } else { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; daddr = inet->daddr; dport = inet->dport; /* Open fast path for connected socket. Route will not be used, if at least one option is set. */ connected = 1; } ipc.addr = inet->saddr; ipc.oif = sk->sk_bound_dev_if; if (msg->msg_controllen) { err = ip_cmsg_send(msg, &ipc); if (err) return err; if (ipc.opt) free = 1; connected = 0; } if (!ipc.opt) ipc.opt = inet->opt; saddr = ipc.addr; ipc.addr = faddr = daddr; if (ipc.opt && ipc.opt->srr) { if (!daddr) return -EINVAL; faddr = ipc.opt->faddr; connected = 0; } tos = RT_TOS(inet->tos); if (sock_flag(sk, SOCK_LOCALROUTE) || (msg->msg_flags & MSG_DONTROUTE) || (ipc.opt && ipc.opt->is_strictroute)) { tos |= RTO_ONLINK; connected = 0; } if (MULTICAST(daddr)) { if (!ipc.oif) ipc.oif = inet->mc_index; if (!saddr) saddr = inet->mc_addr; connected = 0; } if (connected) rt = (struct rtable*)sk_dst_check(sk, 0); if (rt == NULL) { struct flowi fl = { .oif = ipc.oif, .nl_u = { .ip4_u = { .daddr = faddr, .saddr = saddr, .tos = tos } }, .proto = IPPROTO_UDP, .uli_u = { .ports = { .sport = inet->sport, .dport = dport } } }; security_sk_classify_flow(sk, &fl); err = ip_route_output_flow(&rt, &fl, sk, !(msg->msg_flags&MSG_DONTWAIT)); if (err) goto out; err = -EACCES; if ((rt->rt_flags & RTCF_BROADCAST) && !sock_flag(sk, SOCK_BROADCAST)) goto out; if (connected) sk_dst_set(sk, dst_clone(&rt->u.dst)); } if (msg->msg_flags&MSG_CONFIRM) goto do_confirm; back_from_confirm: saddr = rt->rt_src; if (!ipc.addr) daddr = ipc.addr = rt->rt_dst; lock_sock(sk); if (unlikely(up->pending)) { /* The socket is already corked while preparing it. */ /* ... which is an evident application bug. --ANK */ release_sock(sk); LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 2\n"); err = -EINVAL; goto out; } /* * Now cork the socket to pend data. */ inet->cork.fl.fl4_dst = daddr; inet->cork.fl.fl_ip_dport = dport; inet->cork.fl.fl4_src = saddr; inet->cork.fl.fl_ip_sport = inet->sport; up->pending = AF_INET; do_append_data: up->len += ulen; err = ip_append_data(sk, ip_generic_getfrag, msg->msg_iov, ulen, sizeof(struct udphdr), &ipc, rt, corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags); if (err) udp_flush_pending_frames(sk); else if (!corkreq) err = udp_push_pending_frames(sk, up); release_sock(sk); out: ip_rt_put(rt); if (free) kfree(ipc.opt); if (!err) { UDP_INC_STATS_USER(UDP_MIB_OUTDATAGRAMS); return len; } /* * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting * ENOBUFS might not be good (it's not tunable per se), but otherwise * we don't have a good statistic (IpOutDiscards but it can be too many * things). We could add another new stat but at least for now that * seems like overkill. */ if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) { UDP_INC_STATS_USER(UDP_MIB_SNDBUFERRORS); } return err; do_confirm: dst_confirm(&rt->u.dst); if (!(msg->msg_flags&MSG_PROBE) || len) goto back_from_confirm; err = 0; goto out; }
int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len) { struct inet_sock *inet = inet_sk(sk); struct udp_sock *up = udp_sk(sk); int ulen = len; struct ipcm_cookie ipc; struct rtable *rt = NULL; int free = 0; int connected = 0; __be32 daddr, faddr, saddr; __be16 dport; u8 tos; int err; int corkreq = up->corkflag || msg->msg_flags&MSG_MORE; if (len > 0xFFFF) return -EMSGSIZE; if (msg->msg_flags&MSG_OOB) return -EOPNOTSUPP; ipc.opt = NULL; if (up->pending) { lock_sock(sk); if (likely(up->pending)) { if (unlikely(up->pending != AF_INET)) { release_sock(sk); return -EINVAL; } goto do_append_data; } release_sock(sk); } ulen += sizeof(struct udphdr); if (msg->msg_name) { struct sockaddr_in * usin = (struct sockaddr_in*)msg->msg_name; if (msg->msg_namelen < sizeof(*usin)) return -EINVAL; if (usin->sin_family != AF_INET) { if (usin->sin_family != AF_UNSPEC) return -EAFNOSUPPORT; } daddr = usin->sin_addr.s_addr; dport = usin->sin_port; if (dport == 0) return -EINVAL; } else { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; daddr = inet->daddr; dport = inet->dport; connected = 1; } ipc.addr = inet->saddr; ipc.oif = sk->sk_bound_dev_if; if (msg->msg_controllen) { err = ip_cmsg_send(msg, &ipc); if (err) return err; if (ipc.opt) free = 1; connected = 0; } if (!ipc.opt) ipc.opt = inet->opt; saddr = ipc.addr; ipc.addr = faddr = daddr; if (ipc.opt && ipc.opt->srr) { if (!daddr) return -EINVAL; faddr = ipc.opt->faddr; connected = 0; } tos = RT_TOS(inet->tos); if (sock_flag(sk, SOCK_LOCALROUTE) || (msg->msg_flags & MSG_DONTROUTE) || (ipc.opt && ipc.opt->is_strictroute)) { tos |= RTO_ONLINK; connected = 0; } if (MULTICAST(daddr)) { if (!ipc.oif) ipc.oif = inet->mc_index; if (!saddr) saddr = inet->mc_addr; connected = 0; } if (connected) rt = (struct rtable*)sk_dst_check(sk, 0); if (rt == NULL) { struct flowi fl = { .oif = ipc.oif, .nl_u = { .ip4_u = { .daddr = faddr, .saddr = saddr, .tos = tos } }, .proto = IPPROTO_UDP, .uli_u = { .ports = { .sport = inet->sport, .dport = dport } } }; security_sk_classify_flow(sk, &fl); err = ip_route_output_flow(&rt, &fl, sk, !(msg->msg_flags&MSG_DONTWAIT)); if (err) goto out; err = -EACCES; if ((rt->rt_flags & RTCF_BROADCAST) && !sock_flag(sk, SOCK_BROADCAST)) goto out; if (connected) sk_dst_set(sk, dst_clone(&rt->u.dst)); } if (msg->msg_flags&MSG_CONFIRM) goto do_confirm; back_from_confirm: saddr = rt->rt_src; if (!ipc.addr) daddr = ipc.addr = rt->rt_dst; lock_sock(sk); if (unlikely(up->pending)) { release_sock(sk); LIMIT_NETDEBUG(KERN_DEBUG "udp cork app bug 2\n"); err = -EINVAL; goto out; } inet->cork.fl.fl4_dst = daddr; inet->cork.fl.fl_ip_dport = dport; inet->cork.fl.fl4_src = saddr; inet->cork.fl.fl_ip_sport = inet->sport; up->pending = AF_INET; do_append_data: up->len += ulen; err = ip_append_data(sk, ip_generic_getfrag, msg->msg_iov, ulen, sizeof(struct udphdr), &ipc, rt, corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags); if (err) udp_flush_pending_frames(sk); else if (!corkreq) err = udp_push_pending_frames(sk, up); release_sock(sk); out: ip_rt_put(rt); if (free) kfree(ipc.opt); if (!err) { UDP_INC_STATS_USER(UDP_MIB_OUTDATAGRAMS); return len; } if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) { UDP_INC_STATS_USER(UDP_MIB_SNDBUFERRORS); } return err; do_confirm: dst_confirm(&rt->u.dst); if (!(msg->msg_flags&MSG_PROBE) || len) goto back_from_confirm; err = 0; goto out; }
1,412
0
TEST_F ( BrowsingDataRemoverImplTest , RemoveProtectedLocalStorageForever ) { # if BUILDFLAG ( ENABLE_EXTENSIONS ) MockExtensionSpecialStoragePolicy * policy = CreateMockPolicy ( ) ; policy -> AddProtected ( kOrigin1 . GetOrigin ( ) ) ; # endif BlockUntilBrowsingDataRemoved ( base : : Time ( ) , base : : Time : : Max ( ) , BrowsingDataRemover : : REMOVE_LOCAL_STORAGE , true ) ; EXPECT_EQ ( BrowsingDataRemover : : REMOVE_LOCAL_STORAGE , GetRemovalMask ( ) ) ; EXPECT_EQ ( BrowsingDataHelper : : UNPROTECTED_WEB | BrowsingDataHelper : : PROTECTED_WEB , GetOriginTypeMask ( ) ) ; StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData ( ) ; EXPECT_EQ ( removal_data . remove_mask , StoragePartition : : REMOVE_DATA_MASK_LOCAL_STORAGE ) ; EXPECT_EQ ( removal_data . quota_storage_remove_mask , StoragePartition : : QUOTA_MANAGED_STORAGE_MASK_ALL ) ; EXPECT_EQ ( removal_data . remove_begin , GetBeginTime ( ) ) ; EXPECT_TRUE ( removal_data . origin_matcher . Run ( kOrigin1 , mock_policy ( ) ) ) ; EXPECT_TRUE ( removal_data . origin_matcher . Run ( kOrigin2 , mock_policy ( ) ) ) ; EXPECT_TRUE ( removal_data . origin_matcher . Run ( kOrigin3 , mock_policy ( ) ) ) ; EXPECT_FALSE ( removal_data . origin_matcher . Run ( kOriginExt , mock_policy ( ) ) ) ; }
TEST_F ( BrowsingDataRemoverImplTest , RemoveProtectedLocalStorageForever ) { # if BUILDFLAG ( ENABLE_EXTENSIONS ) MockExtensionSpecialStoragePolicy * policy = CreateMockPolicy ( ) ; policy -> AddProtected ( kOrigin1 . GetOrigin ( ) ) ; # endif BlockUntilBrowsingDataRemoved ( base : : Time ( ) , base : : Time : : Max ( ) , BrowsingDataRemover : : REMOVE_LOCAL_STORAGE , true ) ; EXPECT_EQ ( BrowsingDataRemover : : REMOVE_LOCAL_STORAGE , GetRemovalMask ( ) ) ; EXPECT_EQ ( BrowsingDataHelper : : UNPROTECTED_WEB | BrowsingDataHelper : : PROTECTED_WEB , GetOriginTypeMask ( ) ) ; StoragePartitionRemovalData removal_data = GetStoragePartitionRemovalData ( ) ; EXPECT_EQ ( removal_data . remove_mask , StoragePartition : : REMOVE_DATA_MASK_LOCAL_STORAGE ) ; EXPECT_EQ ( removal_data . quota_storage_remove_mask , StoragePartition : : QUOTA_MANAGED_STORAGE_MASK_ALL ) ; EXPECT_EQ ( removal_data . remove_begin , GetBeginTime ( ) ) ; EXPECT_TRUE ( removal_data . origin_matcher . Run ( kOrigin1 , mock_policy ( ) ) ) ; EXPECT_TRUE ( removal_data . origin_matcher . Run ( kOrigin2 , mock_policy ( ) ) ) ; EXPECT_TRUE ( removal_data . origin_matcher . Run ( kOrigin3 , mock_policy ( ) ) ) ; EXPECT_FALSE ( removal_data . origin_matcher . Run ( kOriginExt , mock_policy ( ) ) ) ; }
1,413
0
bool JSON_parser(Variant &z, const char *p, int length, bool const assoc, int depth, int64_t options) { // No GC safepoints during JSON parsing, please. Code is not re-entrant. NoHandleSurpriseScope no_surprise(SafepointFlags); json_parser *json = s_json_parser.get(); /* the parser state */ // Clear and reuse the thread-local string buffers. They are only freed if // they exceed kMaxPersistentStringBufferCapacity at exit or if the thread // is explicitly flushed (e.g., due to being idle). json->initSb(length); if (depth <= 0) { json->error_code = json_error_codes::JSON_ERROR_DEPTH; return false; } SCOPE_EXIT { constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024; if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb(); }; // SimpleParser only handles the most common set of options. Also, only use it // if its array nesting depth check is *more* restrictive than what the user // asks for, to ensure that the precise semantics of the general case is // applied for all nesting overflows. if (assoc && options == (options & (k_JSON_FB_LOOSE | k_JSON_FB_DARRAYS | k_JSON_FB_DARRAYS_AND_VARRAYS | k_JSON_FB_HACK_ARRAYS | k_JSON_FB_THRIFT_SIMPLE_JSON | k_JSON_FB_LEGACY_HACK_ARRAYS)) && depth >= SimpleParser::kMaxArrayDepth && length <= RuntimeOption::EvalSimpleJsonMaxLength && SimpleParser::TryParse(p, length, json->tl_buffer.tv, z, get_container_type_from_options(options), options & k_JSON_FB_THRIFT_SIMPLE_JSON)) { return true; } int b; /* the next character */ int c; /* the next character class */ int s; /* the next state */ int state = 0; /*<fb>*/ bool const loose = options & k_JSON_FB_LOOSE; JSONContainerType const container_type = get_container_type_from_options(options); int qchr = 0; int8_t const *byte_class; int8_t const (*next_state_table)[32]; if (loose) { byte_class = loose_ascii_class; next_state_table = loose_state_transition_table; } else { byte_class = ascii_class; next_state_table = state_transition_table; } /*</fb>*/ UncheckedBuffer *buf = &json->sb_buf; UncheckedBuffer *key = &json->sb_key; DataType type = kInvalidDataType; unsigned short escaped_bytes = 0; auto reset_type = [&] { type = kInvalidDataType; }; json->depth = depth; // Since the stack is maintainined on a per request basis, for performance // reasons, it only makes sense to expand if necessary and cycles are wasted // contracting. Calls with a depth other than default should be rare. if (depth > json->stack.size()) { json->stack.resize(depth); } SCOPE_EXIT { if (json->stack.empty()) return; for (int i = 0; i <= json->mark; i++) { json->stack[i].key.reset(); json->stack[i].val.unset(); } json->mark = -1; }; json->mark = json->top = -1; push(json, Mode::DONE); UTF8To16Decoder decoder(p, length, loose); for (;;) { b = decoder.decode(); // Fast-case most common transition: append a simple string character. if (state == 3 && type == KindOfString) { while (b != '\"' && b != '\\' && b != '\'' && b <= 127 && b >= ' ') { buf->append((char)b); b = decoder.decode(); } } if (b == UTF8_END) break; // UTF-8 decoding finishes successfully. if (b == UTF8_ERROR) { s_json_parser->error_code = JSON_ERROR_UTF8; return false; } assertx(b >= 0); if ((b & 127) == b) { /*<fb>*/ c = byte_class[b]; /*</fb>*/ if (c <= S_ERR) { s_json_parser->error_code = JSON_ERROR_CTRL_CHAR; return false; } } else { c = S_ETC; } /* Get the next state from the transition table. */ /*<fb>*/ s = next_state_table[state][c]; if (s == -4) { if (b != qchr) { s = 3; } else { qchr = 0; } } /*</fb>*/ if (s < 0) { /* Perform one of the predefined actions. */ switch (s) { /* empty } */ case -9: /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::KEY)) { return false; } state = 9; break; /* { */ case -8: if (!push(json, Mode::KEY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 1; if (json->top > 0) { Variant &top = json->stack[json->top].val; /*<fb>*/ if (container_type == JSONContainerType::COLLECTIONS) { // stable_maps is meaningless top = req::make<c_Map>(); } else { /*</fb>*/ if (!assoc) { top = SystemLib::AllocStdClassObject(); /* <fb> */ } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateDict(); } else if (container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateDArray(); /* </fb> */ } else if ( container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyDictArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /*<fb>*/ } /*</fb>*/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* } */ case -7: /*** BEGIN Facebook: json_utf8_loose ***/ /* If this is a trailing comma in an object definition, we're in Mode::KEY. In that case, throw that off the stack and restore Mode::OBJECT so that we pretend the trailing comma just didn't happen. */ if (loose) { if (pop(json, Mode::KEY)) { push(json, Mode::OBJECT); } } /*** END Facebook: json_utf8_loose ***/ if (type != kInvalidDataType && json->stack[json->top].mode == Mode::OBJECT) { Variant mval; json_create_zval(mval, *buf, type, options); Variant &top = json->stack[json->top].val; object_set(json, top, copy_and_clear(*key), mval, assoc, container_type); buf->clear(); reset_type(); } /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::OBJECT)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; break; /* [ */ case -6: if (!push(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 2; if (json->top > 0) { Variant &top = json->stack[json->top].val; /*<fb>*/ if (container_type == JSONContainerType::COLLECTIONS) { top = req::make<c_Vector>(); } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateVec(); } else if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateVArray(); } else if (container_type == JSONContainerType::DARRAYS) { top = Array::CreateDArray(); } else if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyVecArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /*</fb>*/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* ] */ case -5: { if (type != kInvalidDataType && json->stack[json->top].mode == Mode::ARRAY) { Variant mval; json_create_zval(mval, *buf, type, options); auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } buf->clear(); reset_type(); } /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; } break; /* " */ case -4: switch (json->stack[json->top].mode) { case Mode::KEY: state = 27; std::swap(buf, key); reset_type(); break; case Mode::ARRAY: case Mode::OBJECT: state = 9; break; case Mode::DONE: if (type == KindOfString) { z = copy_and_clear(*buf); state = 9; break; } /* fall through if not KindOfString */ default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } break; /* , */ case -3: { Variant mval; if (type != kInvalidDataType && (json->stack[json->top].mode == Mode::OBJECT || json->stack[json->top].mode == Mode::ARRAY)) { json_create_zval(mval, *buf, type, options); } switch (json->stack[json->top].mode) { case Mode::OBJECT: if (pop(json, Mode::OBJECT) && push(json, Mode::KEY)) { if (type != kInvalidDataType) { Variant &top = json->stack[json->top].val; object_set( json, top, copy_and_clear(*key), mval, assoc, container_type ); } state = 29; } break; case Mode::ARRAY: if (type != kInvalidDataType) { auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } } state = 28; break; default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } buf->clear(); reset_type(); check_non_safepoint_surprise(); } break; /*<fb>*/ /* : (after unquoted string) */ case -10: if (json->stack[json->top].mode == Mode::KEY) { state = 27; std::swap(buf, key); reset_type(); s = -2; } else { s = 3; break; } /*</fb>*/ /* : */ case -2: if (pop(json, Mode::KEY) && push(json, Mode::OBJECT)) { state = 28; break; } /* syntax error */ case -1: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { /* Change the state and iterate. */ bool is_tsimplejson = options & k_JSON_FB_THRIFT_SIMPLE_JSON; if (type == KindOfString) { if (/*<fb>*/(/*</fb>*/s == 3/*<fb>*/ || s == 30)/*</fb>*/ && state != 8) { if (state != 4) { utf16_to_utf8(*buf, b); } else { switch (b) { case 'b': buf->append('\b'); break; case 't': buf->append('\t'); break; case 'n': buf->append('\n'); break; case 'f': buf->append('\f'); break; case 'r': buf->append('\r'); break; default: utf16_to_utf8(*buf, b); break; } } } else if (s == 6) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } escaped_bytes = 0; } else { escaped_bytes = dehexchar(b) << 12; } } else if (s == 7) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { escaped_bytes += dehexchar(b) << 8; } } else if (s == 8) { escaped_bytes += dehexchar(b) << 4; } else if (s == 3 && state == 8) { escaped_bytes += dehexchar(b); if (UNLIKELY(is_tsimplejson)) { buf->append((char)escaped_bytes); } else { utf16_to_utf8(*buf, escaped_bytes); } } } else if ((type == kInvalidDataType || type == KindOfNull) && (c == S_DIG || c == S_ZER)) { type = KindOfInt64; buf->append((char)b); } else if (type == KindOfInt64 && s == 24) { type = KindOfDouble; buf->append((char)b); } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64) && c == S_DOT) { type = KindOfDouble; buf->append((char)b); } else if (type != KindOfString && c == S_QUO) { type = KindOfString; /*<fb>*/qchr = b;/*</fb>*/ } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64 || type == KindOfDouble) && ((state == 12 && s == 9) || (state == 16 && s == 9))) { type = KindOfBoolean; } else if (type == kInvalidDataType && state == 19 && s == 9) { type = KindOfNull; } else if (type != KindOfString && c > S_WSP) { utf16_to_utf8(*buf, b); } state = s; } } if (state == 9 && pop(json, Mode::DONE)) { s_json_parser->error_code = JSON_ERROR_NONE; return true; } s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; }
bool JSON_parser(Variant &z, const char *p, int length, bool const assoc, int depth, int64_t options) { NoHandleSurpriseScope no_surprise(SafepointFlags); json_parser *json = s_json_parser.get(); json->initSb(length); if (depth <= 0) { json->error_code = json_error_codes::JSON_ERROR_DEPTH; return false; } SCOPE_EXIT { constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024; if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb(); }; if (assoc && options == (options & (k_JSON_FB_LOOSE | k_JSON_FB_DARRAYS | k_JSON_FB_DARRAYS_AND_VARRAYS | k_JSON_FB_HACK_ARRAYS | k_JSON_FB_THRIFT_SIMPLE_JSON | k_JSON_FB_LEGACY_HACK_ARRAYS)) && depth >= SimpleParser::kMaxArrayDepth && length <= RuntimeOption::EvalSimpleJsonMaxLength && SimpleParser::TryParse(p, length, json->tl_buffer.tv, z, get_container_type_from_options(options), options & k_JSON_FB_THRIFT_SIMPLE_JSON)) { return true; } int b; int c; int s; int state = 0; bool const loose = options & k_JSON_FB_LOOSE; JSONContainerType const container_type = get_container_type_from_options(options); int qchr = 0; int8_t const *byte_class; int8_t const (*next_state_table)[32]; if (loose) { byte_class = loose_ascii_class; next_state_table = loose_state_transition_table; } else { byte_class = ascii_class; next_state_table = state_transition_table; } UncheckedBuffer *buf = &json->sb_buf; UncheckedBuffer *key = &json->sb_key; DataType type = kInvalidDataType; unsigned short escaped_bytes = 0; auto reset_type = [&] { type = kInvalidDataType; }; json->depth = depth; if (depth > json->stack.size()) { json->stack.resize(depth); } SCOPE_EXIT { if (json->stack.empty()) return; for (int i = 0; i <= json->mark; i++) { json->stack[i].key.reset(); json->stack[i].val.unset(); } json->mark = -1; }; json->mark = json->top = -1; push(json, Mode::DONE); UTF8To16Decoder decoder(p, length, loose); for (;;) { b = decoder.decode(); if (state == 3 && type == KindOfString) { while (b != '\"' && b != '\\' && b != '\'' && b <= 127 && b >= ' ') { buf->append((char)b); b = decoder.decode(); } } if (b == UTF8_END) break; if (b == UTF8_ERROR) { s_json_parser->error_code = JSON_ERROR_UTF8; return false; } assertx(b >= 0); if ((b & 127) == b) { c = byte_class[b]; if (c <= S_ERR) { s_json_parser->error_code = JSON_ERROR_CTRL_CHAR; return false; } } else { c = S_ETC; } s = next_state_table[state][c]; if (s == -4) { if (b != qchr) { s = 3; } else { qchr = 0; } } if (s < 0) { switch (s) { case -9: if (json->top == 1) z = json->stack[json->top].val; else { attach_zval(json, json->stack[json->top].key, assoc, container_type); } if (!pop(json, Mode::KEY)) { return false; } state = 9; break; case -8: if (!push(json, Mode::KEY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 1; if (json->top > 0) { Variant &top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { top = req::make<c_Map>(); } else { if (!assoc) { top = SystemLib::AllocStdClassObject(); } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateDict(); } else if (container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateDArray(); } else if ( container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyDictArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } } json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; case -7: if (loose) { if (pop(json, Mode::KEY)) { push(json, Mode::OBJECT); } } if (type != kInvalidDataType && json->stack[json->top].mode == Mode::OBJECT) { Variant mval; json_create_zval(mval, *buf, type, options); Variant &top = json->stack[json->top].val; object_set(json, top, copy_and_clear(*key), mval, assoc, container_type); buf->clear(); reset_type(); } if (json->top == 1) z = json->stack[json->top].val; else { attach_zval(json, json->stack[json->top].key, assoc, container_type); } if (!pop(json, Mode::OBJECT)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; break; case -6: if (!push(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 2; if (json->top > 0) { Variant &top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { top = req::make<c_Vector>(); } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateVec(); } else if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateVArray(); } else if (container_type == JSONContainerType::DARRAYS) { top = Array::CreateDArray(); } else if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyVecArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; case -5: { if (type != kInvalidDataType && json->stack[json->top].mode == Mode::ARRAY) { Variant mval; json_create_zval(mval, *buf, type, options); auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } buf->clear(); reset_type(); } if (json->top == 1) z = json->stack[json->top].val; else { attach_zval(json, json->stack[json->top].key, assoc, container_type); } if (!pop(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; } break; case -4: switch (json->stack[json->top].mode) { case Mode::KEY: state = 27; std::swap(buf, key); reset_type(); break; case Mode::ARRAY: case Mode::OBJECT: state = 9; break; case Mode::DONE: if (type == KindOfString) { z = copy_and_clear(*buf); state = 9; break; } default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } break; case -3: { Variant mval; if (type != kInvalidDataType && (json->stack[json->top].mode == Mode::OBJECT || json->stack[json->top].mode == Mode::ARRAY)) { json_create_zval(mval, *buf, type, options); } switch (json->stack[json->top].mode) { case Mode::OBJECT: if (pop(json, Mode::OBJECT) && push(json, Mode::KEY)) { if (type != kInvalidDataType) { Variant &top = json->stack[json->top].val; object_set( json, top, copy_and_clear(*key), mval, assoc, container_type ); } state = 29; } break; case Mode::ARRAY: if (type != kInvalidDataType) { auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } } state = 28; break; default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } buf->clear(); reset_type(); check_non_safepoint_surprise(); } break; case -10: if (json->stack[json->top].mode == Mode::KEY) { state = 27; std::swap(buf, key); reset_type(); s = -2; } else { s = 3; break; } case -2: if (pop(json, Mode::KEY) && push(json, Mode::OBJECT)) { state = 28; break; } case -1: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { bool is_tsimplejson = options & k_JSON_FB_THRIFT_SIMPLE_JSON; if (type == KindOfString) { if ( ( s == 3 || s == 30) && state != 8) { if (state != 4) { utf16_to_utf8(*buf, b); } else { switch (b) { case 'b': buf->append('\b'); break; case 't': buf->append('\t'); break; case 'n': buf->append('\n'); break; case 'f': buf->append('\f'); break; case 'r': buf->append('\r'); break; default: utf16_to_utf8(*buf, b); break; } } } else if (s == 6) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } escaped_bytes = 0; } else { escaped_bytes = dehexchar(b) << 12; } } else if (s == 7) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { escaped_bytes += dehexchar(b) << 8; } } else if (s == 8) { escaped_bytes += dehexchar(b) << 4; } else if (s == 3 && state == 8) { escaped_bytes += dehexchar(b); if (UNLIKELY(is_tsimplejson)) { buf->append((char)escaped_bytes); } else { utf16_to_utf8(*buf, escaped_bytes); } } } else if ((type == kInvalidDataType || type == KindOfNull) && (c == S_DIG || c == S_ZER)) { type = KindOfInt64; buf->append((char)b); } else if (type == KindOfInt64 && s == 24) { type = KindOfDouble; buf->append((char)b); } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64) && c == S_DOT) { type = KindOfDouble; buf->append((char)b); } else if (type != KindOfString && c == S_QUO) { type = KindOfString; qchr = b; } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64 || type == KindOfDouble) && ((state == 12 && s == 9) || (state == 16 && s == 9))) { type = KindOfBoolean; } else if (type == kInvalidDataType && state == 19 && s == 9) { type = KindOfNull; } else if (type != KindOfString && c > S_WSP) { utf16_to_utf8(*buf, b); } state = s; } } if (state == 9 && pop(json, Mode::DONE)) { s_json_parser->error_code = JSON_ERROR_NONE; return true; } s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; }
1,415
1
midi_synth_load_patch(int dev, int format, const char __user *addr, int offs, int count, int pmgr_flag) { int orig_dev = synth_devs[dev]->midi_dev; struct sysex_info sysex; int i; unsigned long left, src_offs, eox_seen = 0; int first_byte = 1; int hdr_size = (unsigned long) &sysex.data[0] - (unsigned long) &sysex; leave_sysex(dev); if (!prefix_cmd(orig_dev, 0xf0)) return 0; if (format != SYSEX_PATCH) { /* printk("MIDI Error: Invalid patch format (key) 0x%x\n", format);*/ return -EINVAL; } if (count < hdr_size) { /* printk("MIDI Error: Patch header too short\n");*/ return -EINVAL; } count -= hdr_size; /* * Copy the header from user space but ignore the first bytes which have * been transferred already. */ if(copy_from_user(&((char *) &sysex)[offs], &(addr)[offs], hdr_size - offs)) return -EFAULT; if (count < sysex.len) { /* printk(KERN_WARNING "MIDI Warning: Sysex record too short (%d<%d)\n", count, (int) sysex.len);*/ sysex.len = count; } left = sysex.len; src_offs = 0; for (i = 0; i < left && !signal_pending(current); i++) { unsigned char data; if (get_user(data, (unsigned char __user *)(addr + hdr_size + i))) return -EFAULT; eox_seen = (i > 0 && data & 0x80); /* End of sysex */ if (eox_seen && data != 0xf7) data = 0xf7; if (i == 0) { if (data != 0xf0) { printk(KERN_WARNING "midi_synth: Sysex start missing\n"); return -EINVAL; } } while (!midi_devs[orig_dev]->outputc(orig_dev, (unsigned char) (data & 0xff)) && !signal_pending(current)) schedule(); if (!first_byte && data & 0x80) return 0; first_byte = 0; } if (!eox_seen) midi_outc(orig_dev, 0xf7); return 0; }
midi_synth_load_patch(int dev, int format, const char __user *addr, int offs, int count, int pmgr_flag) { int orig_dev = synth_devs[dev]->midi_dev; struct sysex_info sysex; int i; unsigned long left, src_offs, eox_seen = 0; int first_byte = 1; int hdr_size = (unsigned long) &sysex.data[0] - (unsigned long) &sysex; leave_sysex(dev); if (!prefix_cmd(orig_dev, 0xf0)) return 0; if (format != SYSEX_PATCH) { return -EINVAL; } if (count < hdr_size) { return -EINVAL; } count -= hdr_size; if(copy_from_user(&((char *) &sysex)[offs], &(addr)[offs], hdr_size - offs)) return -EFAULT; if (count < sysex.len) { sysex.len = count; } left = sysex.len; src_offs = 0; for (i = 0; i < left && !signal_pending(current); i++) { unsigned char data; if (get_user(data, (unsigned char __user *)(addr + hdr_size + i))) return -EFAULT; eox_seen = (i > 0 && data & 0x80); if (eox_seen && data != 0xf7) data = 0xf7; if (i == 0) { if (data != 0xf0) { printk(KERN_WARNING "midi_synth: Sysex start missing\n"); return -EINVAL; } } while (!midi_devs[orig_dev]->outputc(orig_dev, (unsigned char) (data & 0xff)) && !signal_pending(current)) schedule(); if (!first_byte && data & 0x80) return 0; first_byte = 0; } if (!eox_seen) midi_outc(orig_dev, 0xf7); return 0; }
1,416
0
static bool TryParse(const char* inp, int length, TypedValue* buf, Variant& out, JSONContainerType container_type, bool is_tsimplejson) { SimpleParser parser(inp, length, buf, container_type, is_tsimplejson); bool ok = parser.parseValue(); if (!ok || (parser.skipSpace(), parser.p != inp + length)) { // Unsupported, malformed, or trailing garbage. Release entire stack. tvDecRefRange(buf, parser.top); return false; } out = Variant::attach(*--parser.top); return true; }
static bool TryParse(const char* inp, int length, TypedValue* buf, Variant& out, JSONContainerType container_type, bool is_tsimplejson) { SimpleParser parser(inp, length, buf, container_type, is_tsimplejson); bool ok = parser.parseValue(); if (!ok || (parser.skipSpace(), parser.p != inp + length)) { tvDecRefRange(buf, parser.top); return false; } out = Variant::attach(*--parser.top); return true; }
1,417
0
static void cirrus_bitblt_cputovideo_next ( CirrusVGAState * s ) { int copy_count ; uint8_t * end_ptr ; if ( s -> cirrus_srccounter > 0 ) { if ( s -> cirrus_blt_mode & CIRRUS_BLTMODE_PATTERNCOPY ) { cirrus_bitblt_common_patterncopy ( s ) ; the_end : s -> cirrus_srccounter = 0 ; cirrus_bitblt_reset ( s ) ; } else { do { ( * s -> cirrus_rop ) ( s , s -> cirrus_blt_dstaddr , 0 , 0 , 0 , s -> cirrus_blt_width , 1 ) ; cirrus_invalidate_region ( s , s -> cirrus_blt_dstaddr , 0 , s -> cirrus_blt_width , 1 ) ; s -> cirrus_blt_dstaddr += s -> cirrus_blt_dstpitch ; s -> cirrus_srccounter -= s -> cirrus_blt_srcpitch ; if ( s -> cirrus_srccounter <= 0 ) goto the_end ; end_ptr = s -> cirrus_bltbuf + s -> cirrus_blt_srcpitch ; copy_count = s -> cirrus_srcptr_end - end_ptr ; memmove ( s -> cirrus_bltbuf , end_ptr , copy_count ) ; s -> cirrus_srcptr = s -> cirrus_bltbuf + copy_count ; s -> cirrus_srcptr_end = s -> cirrus_bltbuf + s -> cirrus_blt_srcpitch ; } while ( s -> cirrus_srcptr >= s -> cirrus_srcptr_end ) ; } } }
static void cirrus_bitblt_cputovideo_next ( CirrusVGAState * s ) { int copy_count ; uint8_t * end_ptr ; if ( s -> cirrus_srccounter > 0 ) { if ( s -> cirrus_blt_mode & CIRRUS_BLTMODE_PATTERNCOPY ) { cirrus_bitblt_common_patterncopy ( s ) ; the_end : s -> cirrus_srccounter = 0 ; cirrus_bitblt_reset ( s ) ; } else { do { ( * s -> cirrus_rop ) ( s , s -> cirrus_blt_dstaddr , 0 , 0 , 0 , s -> cirrus_blt_width , 1 ) ; cirrus_invalidate_region ( s , s -> cirrus_blt_dstaddr , 0 , s -> cirrus_blt_width , 1 ) ; s -> cirrus_blt_dstaddr += s -> cirrus_blt_dstpitch ; s -> cirrus_srccounter -= s -> cirrus_blt_srcpitch ; if ( s -> cirrus_srccounter <= 0 ) goto the_end ; end_ptr = s -> cirrus_bltbuf + s -> cirrus_blt_srcpitch ; copy_count = s -> cirrus_srcptr_end - end_ptr ; memmove ( s -> cirrus_bltbuf , end_ptr , copy_count ) ; s -> cirrus_srcptr = s -> cirrus_bltbuf + copy_count ; s -> cirrus_srcptr_end = s -> cirrus_bltbuf + s -> cirrus_blt_srcpitch ; } while ( s -> cirrus_srcptr >= s -> cirrus_srcptr_end ) ; } } }
1,420
1
static int llc_ui_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddrlen, int peer) { struct sockaddr_llc sllc; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); int rc = 0; lock_sock(sk); if (sock_flag(sk, SOCK_ZAPPED)) goto out; *uaddrlen = sizeof(sllc); memset(uaddr, 0, *uaddrlen); if (peer) { rc = -ENOTCONN; if (sk->sk_state != TCP_ESTABLISHED) goto out; if(llc->dev) sllc.sllc_arphrd = llc->dev->type; sllc.sllc_sap = llc->daddr.lsap; memcpy(&sllc.sllc_mac, &llc->daddr.mac, IFHWADDRLEN); } else { rc = -EINVAL; if (!llc->sap) goto out; sllc.sllc_sap = llc->sap->laddr.lsap; if (llc->dev) { sllc.sllc_arphrd = llc->dev->type; memcpy(&sllc.sllc_mac, llc->dev->dev_addr, IFHWADDRLEN); } } rc = 0; sllc.sllc_family = AF_LLC; memcpy(uaddr, &sllc, sizeof(sllc)); out: release_sock(sk); return rc; }
static int llc_ui_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddrlen, int peer) { struct sockaddr_llc sllc; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); int rc = 0; lock_sock(sk); if (sock_flag(sk, SOCK_ZAPPED)) goto out; *uaddrlen = sizeof(sllc); memset(uaddr, 0, *uaddrlen); if (peer) { rc = -ENOTCONN; if (sk->sk_state != TCP_ESTABLISHED) goto out; if(llc->dev) sllc.sllc_arphrd = llc->dev->type; sllc.sllc_sap = llc->daddr.lsap; memcpy(&sllc.sllc_mac, &llc->daddr.mac, IFHWADDRLEN); } else { rc = -EINVAL; if (!llc->sap) goto out; sllc.sllc_sap = llc->sap->laddr.lsap; if (llc->dev) { sllc.sllc_arphrd = llc->dev->type; memcpy(&sllc.sllc_mac, llc->dev->dev_addr, IFHWADDRLEN); } } rc = 0; sllc.sllc_family = AF_LLC; memcpy(uaddr, &sllc, sizeof(sllc)); out: release_sock(sk); return rc; }
1,421
1
static bool TryParse(const char* inp, int length, TypedValue* buf, Variant& out, JSONContainerType container_type, bool is_tsimplejson) { SimpleParser parser(inp, length, buf, container_type, is_tsimplejson); bool ok = parser.parseValue(); parser.skipSpace(); if (!ok || parser.p != inp + length) { // Unsupported, malformed, or trailing garbage. Release entire stack. tvDecRefRange(buf, parser.top); return false; } out = Variant::attach(*--parser.top); return true; }
static bool TryParse(const char* inp, int length, TypedValue* buf, Variant& out, JSONContainerType container_type, bool is_tsimplejson) { SimpleParser parser(inp, length, buf, container_type, is_tsimplejson); bool ok = parser.parseValue(); parser.skipSpace(); if (!ok || parser.p != inp + length) { tvDecRefRange(buf, parser.top); return false; } out = Variant::attach(*--parser.top); return true; }
1,422
1
static int opl3_load_patch(int dev, int format, const char __user *addr, int offs, int count, int pmgr_flag) { struct sbi_instrument ins; if (count <sizeof(ins)) { printk(KERN_WARNING "FM Error: Patch record too short\n"); return -EINVAL; } /* * What the fuck is going on here? We leave junk in the beginning * of ins and then check the field pretty close to that beginning? */ if(copy_from_user(&((char *) &ins)[offs], addr + offs, sizeof(ins) - offs)) return -EFAULT; if (ins.channel < 0 || ins.channel >= SBFM_MAXINSTR) { printk(KERN_WARNING "FM Error: Invalid instrument number %d\n", ins.channel); return -EINVAL; } ins.key = format; return store_instr(ins.channel, &ins); }
static int opl3_load_patch(int dev, int format, const char __user *addr, int offs, int count, int pmgr_flag) { struct sbi_instrument ins; if (count <sizeof(ins)) { printk(KERN_WARNING "FM Error: Patch record too short\n"); return -EINVAL; } if(copy_from_user(&((char *) &ins)[offs], addr + offs, sizeof(ins) - offs)) return -EFAULT; if (ins.channel < 0 || ins.channel >= SBFM_MAXINSTR) { printk(KERN_WARNING "FM Error: Invalid instrument number %d\n", ins.channel); return -EINVAL; } ins.key = format; return store_instr(ins.channel, &ins); }
1,423
1
static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len) { int i; uint16_t limit; switch (data[0]) { case 0: if (len == 1) return 20; set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5), read_u8(data, 6), read_u8(data, 7), read_u16(data, 8), read_u16(data, 10), read_u16(data, 12), read_u8(data, 14), read_u8(data, 15), read_u8(data, 16)); break; case 2: if (len == 1) return 4; if (len == 4) return 4 + (read_u16(data, 2) * 4); limit = read_u16(data, 2); for (i = 0; i < limit; i++) { int32_t val = read_s32(data, 4 + (i * 4)); memcpy(data + 4 + (i * 4), &val, sizeof(val)); } set_encodings(vs, (int32_t *)(data + 4), limit); break; case 3: if (len == 1) return 10; framebuffer_update_request(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4), read_u16(data, 6), read_u16(data, 8)); break; case 4: if (len == 1) return 8; key_event(vs, read_u8(data, 1), read_u32(data, 4)); break; case 5: if (len == 1) return 6; pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4)); break; case 6: if (len == 1) return 8; if (len == 8) { uint32_t dlen = read_u32(data, 4); if (dlen > 0) return 8 + dlen; } client_cut_text(vs, read_u32(data, 4), data + 8); break; case 255: if (len == 1) return 2; switch (read_u8(data, 1)) { case 0: if (len == 2) return 12; ext_key_event(vs, read_u16(data, 2), read_u32(data, 4), read_u32(data, 8)); break; case 1: if (len == 2) return 4; switch (read_u16 (data, 2)) { case 0: audio_add(vs); break; case 1: audio_del(vs); break; case 2: if (len == 4) return 10; switch (read_u8(data, 4)) { case 0: vs->as.fmt = AUD_FMT_U8; break; case 1: vs->as.fmt = AUD_FMT_S8; break; case 2: vs->as.fmt = AUD_FMT_U16; break; case 3: vs->as.fmt = AUD_FMT_S16; break; case 4: vs->as.fmt = AUD_FMT_U32; break; case 5: vs->as.fmt = AUD_FMT_S32; break; default: printf("Invalid audio format %d\n", read_u8(data, 4)); vnc_client_error(vs); break; } vs->as.nchannels = read_u8(data, 5); if (vs->as.nchannels != 1 && vs->as.nchannels != 2) { printf("Invalid audio channel coount %d\n", read_u8(data, 5)); vnc_client_error(vs); break; } vs->as.freq = read_u32(data, 6); break; default: printf ("Invalid audio message %d\n", read_u8(data, 4)); vnc_client_error(vs); break; } break; default: printf("Msg: %d\n", read_u16(data, 0)); vnc_client_error(vs); break; } break; default: printf("Msg: %d\n", data[0]); vnc_client_error(vs); break; } vnc_read_when(vs, protocol_client_msg, 1); return 0; }
static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len) { int i; uint16_t limit; switch (data[0]) { case 0: if (len == 1) return 20; set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5), read_u8(data, 6), read_u8(data, 7), read_u16(data, 8), read_u16(data, 10), read_u16(data, 12), read_u8(data, 14), read_u8(data, 15), read_u8(data, 16)); break; case 2: if (len == 1) return 4; if (len == 4) return 4 + (read_u16(data, 2) * 4); limit = read_u16(data, 2); for (i = 0; i < limit; i++) { int32_t val = read_s32(data, 4 + (i * 4)); memcpy(data + 4 + (i * 4), &val, sizeof(val)); } set_encodings(vs, (int32_t *)(data + 4), limit); break; case 3: if (len == 1) return 10; framebuffer_update_request(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4), read_u16(data, 6), read_u16(data, 8)); break; case 4: if (len == 1) return 8; key_event(vs, read_u8(data, 1), read_u32(data, 4)); break; case 5: if (len == 1) return 6; pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4)); break; case 6: if (len == 1) return 8; if (len == 8) { uint32_t dlen = read_u32(data, 4); if (dlen > 0) return 8 + dlen; } client_cut_text(vs, read_u32(data, 4), data + 8); break; case 255: if (len == 1) return 2; switch (read_u8(data, 1)) { case 0: if (len == 2) return 12; ext_key_event(vs, read_u16(data, 2), read_u32(data, 4), read_u32(data, 8)); break; case 1: if (len == 2) return 4; switch (read_u16 (data, 2)) { case 0: audio_add(vs); break; case 1: audio_del(vs); break; case 2: if (len == 4) return 10; switch (read_u8(data, 4)) { case 0: vs->as.fmt = AUD_FMT_U8; break; case 1: vs->as.fmt = AUD_FMT_S8; break; case 2: vs->as.fmt = AUD_FMT_U16; break; case 3: vs->as.fmt = AUD_FMT_S16; break; case 4: vs->as.fmt = AUD_FMT_U32; break; case 5: vs->as.fmt = AUD_FMT_S32; break; default: printf("Invalid audio format %d\n", read_u8(data, 4)); vnc_client_error(vs); break; } vs->as.nchannels = read_u8(data, 5); if (vs->as.nchannels != 1 && vs->as.nchannels != 2) { printf("Invalid audio channel coount %d\n", read_u8(data, 5)); vnc_client_error(vs); break; } vs->as.freq = read_u32(data, 6); break; default: printf ("Invalid audio message %d\n", read_u8(data, 4)); vnc_client_error(vs); break; } break; default: printf("Msg: %d\n", read_u16(data, 0)); vnc_client_error(vs); break; } break; default: printf("Msg: %d\n", data[0]); vnc_client_error(vs); break; } vnc_read_when(vs, protocol_client_msg, 1); return 0; }
1,424
1
static int irda_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sockaddr_irda saddr; struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); if (peer) { if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; saddr.sir_family = AF_IRDA; saddr.sir_lsap_sel = self->dtsap_sel; saddr.sir_addr = self->daddr; } else { saddr.sir_family = AF_IRDA; saddr.sir_lsap_sel = self->stsap_sel; saddr.sir_addr = self->saddr; } IRDA_DEBUG(1, "%s(), tsap_sel = %#x\n", __func__, saddr.sir_lsap_sel); IRDA_DEBUG(1, "%s(), addr = %08x\n", __func__, saddr.sir_addr); /* uaddr_len come to us uninitialised */ *uaddr_len = sizeof (struct sockaddr_irda); memcpy(uaddr, &saddr, *uaddr_len); return 0; }
static int irda_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sockaddr_irda saddr; struct sock *sk = sock->sk; struct irda_sock *self = irda_sk(sk); if (peer) { if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; saddr.sir_family = AF_IRDA; saddr.sir_lsap_sel = self->dtsap_sel; saddr.sir_addr = self->daddr; } else { saddr.sir_family = AF_IRDA; saddr.sir_lsap_sel = self->stsap_sel; saddr.sir_addr = self->saddr; } IRDA_DEBUG(1, "%s(), tsap_sel = %#x\n", __func__, saddr.sir_lsap_sel); IRDA_DEBUG(1, "%s(), addr = %08x\n", __func__, saddr.sir_addr); *uaddr_len = sizeof (struct sockaddr_irda); memcpy(uaddr, &saddr, *uaddr_len); return 0; }
1,425
1
static void handle_raw_login ( char * packet , int len , struct query * q , int fd , int userid ) { char myhash [ 16 ] ; if ( len < 16 ) return ; if ( userid < 0 || userid >= created_users ) return ; if ( ! users [ userid ] . active || users [ userid ] . disabled ) return ; if ( users [ userid ] . last_pkt + 60 < time ( NULL ) ) return ; if ( debug >= 1 ) { fprintf ( stderr , "IN login raw, len %d, from user %d\n" , len , userid ) ; } login_calculate ( myhash , 16 , password , users [ userid ] . seed + 1 ) ; if ( memcmp ( packet , myhash , 16 ) == 0 ) { struct sockaddr_in * tempin ; users [ userid ] . last_pkt = time ( NULL ) ; memcpy ( & ( users [ userid ] . q ) , q , sizeof ( struct query ) ) ; tempin = ( struct sockaddr_in * ) & ( q -> from ) ; memcpy ( & ( users [ userid ] . host ) , & ( tempin -> sin_addr ) , sizeof ( struct in_addr ) ) ; user_set_conn_type ( userid , CONN_RAW_UDP ) ; login_calculate ( myhash , 16 , password , users [ userid ] . seed - 1 ) ; send_raw ( fd , myhash , 16 , userid , RAW_HDR_CMD_LOGIN , q ) ; } }
static void handle_raw_login ( char * packet , int len , struct query * q , int fd , int userid ) { char myhash [ 16 ] ; if ( len < 16 ) return ; if ( userid < 0 || userid >= created_users ) return ; if ( ! users [ userid ] . active || users [ userid ] . disabled ) return ; if ( users [ userid ] . last_pkt + 60 < time ( NULL ) ) return ; if ( debug >= 1 ) { fprintf ( stderr , "IN login raw, len %d, from user %d\n" , len , userid ) ; } login_calculate ( myhash , 16 , password , users [ userid ] . seed + 1 ) ; if ( memcmp ( packet , myhash , 16 ) == 0 ) { struct sockaddr_in * tempin ; users [ userid ] . last_pkt = time ( NULL ) ; memcpy ( & ( users [ userid ] . q ) , q , sizeof ( struct query ) ) ; tempin = ( struct sockaddr_in * ) & ( q -> from ) ; memcpy ( & ( users [ userid ] . host ) , & ( tempin -> sin_addr ) , sizeof ( struct in_addr ) ) ; user_set_conn_type ( userid , CONN_RAW_UDP ) ; login_calculate ( myhash , 16 , password , users [ userid ] . seed - 1 ) ; send_raw ( fd , myhash , 16 , userid , RAW_HDR_CMD_LOGIN , q ) ; } }
1,426
1
bool handleBackslash(signed char& out) { char ch = *p++; switch (ch) { case 0: return false; case '"': out = ch; return true; case '\\': out = ch; return true; case '/': out = ch; return true; case 'b': out = '\b'; return true; case 'f': out = '\f'; return true; case 'n': out = '\n'; return true; case 'r': out = '\r'; return true; case 't': out = '\t'; return true; case 'u': { if (UNLIKELY(is_tsimplejson)) { auto const ch1 = *p++; auto const ch2 = *p++; auto const dch3 = dehexchar(*p++); auto const dch4 = dehexchar(*p++); if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) { return false; } out = (dch3 << 4) | dch4; return true; } else { uint16_t u16cp = 0; for (int i = 0; i < 4; i++) { auto const hexv = dehexchar(*p++); if (hexv < 0) return false; // includes check for end of string u16cp <<= 4; u16cp |= hexv; } if (u16cp > 0x7f) { return false; } else { out = u16cp; return true; } } } default: return false; } }
bool handleBackslash(signed char& out) { char ch = *p++; switch (ch) { case 0: return false; case '"': out = ch; return true; case '\\': out = ch; return true; case '/': out = ch; return true; case 'b': out = '\b'; return true; case 'f': out = '\f'; return true; case 'n': out = '\n'; return true; case 'r': out = '\r'; return true; case 't': out = '\t'; return true; case 'u': { if (UNLIKELY(is_tsimplejson)) { auto const ch1 = *p++; auto const ch2 = *p++; auto const dch3 = dehexchar(*p++); auto const dch4 = dehexchar(*p++); if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) { return false; } out = (dch3 << 4) | dch4; return true; } else { uint16_t u16cp = 0; for (int i = 0; i < 4; i++) { auto const hexv = dehexchar(*p++); if (hexv < 0) return false; u16cp <<= 4; u16cp |= hexv; } if (u16cp > 0x7f) { return false; } else { out = u16cp; return true; } } } default: return false; } }
1,427
1
static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; AVSubtitle *sub = data; const uint8_t *buf_end = buf + buf_size; uint8_t *bitmap; int w, h, x, y, i, ret; int64_t packet_time = 0; GetBitContext gb; int has_alpha = avctx->codec_tag == MKTAG('D','X','S','A'); // check that at least header fits if (buf_size < 27 + 7 * 2 + 4 * (3 + has_alpha)) { av_log(avctx, AV_LOG_ERROR, "coded frame size %d too small\n", buf_size); return -1; } // read start and end time if (buf[0] != '[' || buf[13] != '-' || buf[26] != ']') { av_log(avctx, AV_LOG_ERROR, "invalid time code\n"); return -1; } if (avpkt->pts != AV_NOPTS_VALUE) packet_time = av_rescale_q(avpkt->pts, AV_TIME_BASE_Q, (AVRational){1, 1000}); sub->start_display_time = parse_timecode(buf + 1, packet_time); sub->end_display_time = parse_timecode(buf + 14, packet_time); buf += 27; // read header w = bytestream_get_le16(&buf); h = bytestream_get_le16(&buf); if (av_image_check_size(w, h, 0, avctx) < 0) return -1; x = bytestream_get_le16(&buf); y = bytestream_get_le16(&buf); // skip bottom right position, it gives no new information bytestream_get_le16(&buf); bytestream_get_le16(&buf); // The following value is supposed to indicate the start offset // (relative to the palette) of the data for the second field, // however there are files in which it has a bogus value and thus // we just ignore it bytestream_get_le16(&buf); // allocate sub and set values sub->rects = av_mallocz(sizeof(*sub->rects)); if (!sub->rects) return AVERROR(ENOMEM); sub->rects[0] = av_mallocz(sizeof(*sub->rects[0])); if (!sub->rects[0]) { av_freep(&sub->rects); return AVERROR(ENOMEM); } sub->rects[0]->x = x; sub->rects[0]->y = y; sub->rects[0]->w = w; sub->rects[0]->h = h; sub->rects[0]->type = SUBTITLE_BITMAP; sub->rects[0]->linesize[0] = w; sub->rects[0]->data[0] = av_malloc(w * h); sub->rects[0]->nb_colors = 4; sub->rects[0]->data[1] = av_mallocz(AVPALETTE_SIZE); if (!sub->rects[0]->data[0] || !sub->rects[0]->data[1]) { av_freep(&sub->rects[0]->data[1]); av_freep(&sub->rects[0]->data[0]); av_freep(&sub->rects[0]); av_freep(&sub->rects); return AVERROR(ENOMEM); } sub->num_rects = 1; // read palette for (i = 0; i < sub->rects[0]->nb_colors; i++) ((uint32_t*)sub->rects[0]->data[1])[i] = bytestream_get_be24(&buf); if (!has_alpha) { // make all except background (first entry) non-transparent for (i = 1; i < sub->rects[0]->nb_colors; i++) ((uint32_t *)sub->rects[0]->data[1])[i] |= 0xff000000; } else { for (i = 0; i < sub->rects[0]->nb_colors; i++) ((uint32_t *)sub->rects[0]->data[1])[i] |= *buf++ << 24; } #if FF_API_AVPICTURE FF_DISABLE_DEPRECATION_WARNINGS { AVSubtitleRect *rect; int j; rect = sub->rects[0]; for (j = 0; j < 4; j++) { rect->pict.data[j] = rect->data[j]; rect->pict.linesize[j] = rect->linesize[j]; } } FF_ENABLE_DEPRECATION_WARNINGS #endif // process RLE-compressed data if ((ret = init_get_bits8(&gb, buf, buf_end - buf)) < 0) return ret; bitmap = sub->rects[0]->data[0]; for (y = 0; y < h; y++) { // interlaced: do odd lines if (y == (h + 1) / 2) bitmap = sub->rects[0]->data[0] + w; for (x = 0; x < w; ) { int log2 = ff_log2_tab[show_bits(&gb, 8)]; int run = get_bits(&gb, 14 - 4 * (log2 >> 1)); int color = get_bits(&gb, 2); run = FFMIN(run, w - x); // run length 0 means till end of row if (!run) run = w - x; memset(bitmap, color, run); bitmap += run; x += run; } // interlaced, skip every second line bitmap += w; align_get_bits(&gb); } *data_size = 1; return buf_size; }
static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; AVSubtitle *sub = data; const uint8_t *buf_end = buf + buf_size; uint8_t *bitmap; int w, h, x, y, i, ret; int64_t packet_time = 0; GetBitContext gb; int has_alpha = avctx->codec_tag == MKTAG('D','X','S','A');
1,428
0
bool handleBackslash(signed char& out) { char ch = *p++; switch (ch) { case 0: return false; case '"': out = ch; return true; case '\\': out = ch; return true; case '/': out = ch; return true; case 'b': out = '\b'; return true; case 'f': out = '\f'; return true; case 'n': out = '\n'; return true; case 'r': out = '\r'; return true; case 't': out = '\t'; return true; case 'u': { if (UNLIKELY(is_tsimplejson)) { auto const ch1 = *p++; if (UNLIKELY(ch1 != '0')) return false; auto const ch2 = *p++; if (UNLIKELY(ch2 != '0')) return false; auto const dch3 = dehexchar(*p++); if (UNLIKELY(dch3 < 0)) return false; auto const dch4 = dehexchar(*p++); if (UNLIKELY(dch4 < 0)) return false; out = (dch3 << 4) | dch4; return true; } else { uint16_t u16cp = 0; for (int i = 0; i < 4; i++) { auto const hexv = dehexchar(*p++); if (hexv < 0) return false; // includes check for end of string u16cp <<= 4; u16cp |= hexv; } if (u16cp > 0x7f) { return false; } else { out = u16cp; return true; } } } default: return false; } }
bool handleBackslash(signed char& out) { char ch = *p++; switch (ch) { case 0: return false; case '"': out = ch; return true; case '\\': out = ch; return true; case '/': out = ch; return true; case 'b': out = '\b'; return true; case 'f': out = '\f'; return true; case 'n': out = '\n'; return true; case 'r': out = '\r'; return true; case 't': out = '\t'; return true; case 'u': { if (UNLIKELY(is_tsimplejson)) { auto const ch1 = *p++; if (UNLIKELY(ch1 != '0')) return false; auto const ch2 = *p++; if (UNLIKELY(ch2 != '0')) return false; auto const dch3 = dehexchar(*p++); if (UNLIKELY(dch3 < 0)) return false; auto const dch4 = dehexchar(*p++); if (UNLIKELY(dch4 < 0)) return false; out = (dch3 << 4) | dch4; return true; } else { uint16_t u16cp = 0; for (int i = 0; i < 4; i++) { auto const hexv = dehexchar(*p++); if (hexv < 0) return false; u16cp <<= 4; u16cp |= hexv; } if (u16cp > 0x7f) { return false; } else { out = u16cp; return true; } } } default: return false; } }
1,430
1
static void tpm_tis_initfn(Object *obj) { ISADevice *dev = ISA_DEVICE(obj); TPMState *s = TPM(obj); memory_region_init_io(&s->mmio, OBJECT(s), &tpm_tis_memory_ops, s, "tpm-tis-mmio", TPM_TIS_NUM_LOCALITIES << TPM_TIS_LOCALITY_SHIFT); memory_region_add_subregion(isa_address_space(dev), TPM_TIS_ADDR_BASE, &s->mmio); }
static void tpm_tis_initfn(Object *obj) { ISADevice *dev = ISA_DEVICE(obj); TPMState *s = TPM(obj); memory_region_init_io(&s->mmio, OBJECT(s), &tpm_tis_memory_ops, s, "tpm-tis-mmio", TPM_TIS_NUM_LOCALITIES << TPM_TIS_LOCALITY_SHIFT); memory_region_add_subregion(isa_address_space(dev), TPM_TIS_ADDR_BASE, &s->mmio); }
1,431
0
static TranslationBlock * tb_find_pc ( uintptr_t tc_ptr ) { int m_min , m_max , m ; uintptr_t v ; TranslationBlock * tb ; if ( tcg_ctx . tb_ctx . nb_tbs <= 0 ) { return NULL ; } if ( tc_ptr < ( uintptr_t ) tcg_ctx . code_gen_buffer || tc_ptr >= ( uintptr_t ) tcg_ctx . code_gen_ptr ) { return NULL ; } m_min = 0 ; m_max = tcg_ctx . tb_ctx . nb_tbs - 1 ; while ( m_min <= m_max ) { m = ( m_min + m_max ) >> 1 ; tb = & tcg_ctx . tb_ctx . tbs [ m ] ; v = ( uintptr_t ) tb -> tc_ptr ; if ( v == tc_ptr ) { return tb ; } else if ( tc_ptr < v ) { m_max = m - 1 ; } else { m_min = m + 1 ; } } return & tcg_ctx . tb_ctx . tbs [ m_max ] ; }
static TranslationBlock * tb_find_pc ( uintptr_t tc_ptr ) { int m_min , m_max , m ; uintptr_t v ; TranslationBlock * tb ; if ( tcg_ctx . tb_ctx . nb_tbs <= 0 ) { return NULL ; } if ( tc_ptr < ( uintptr_t ) tcg_ctx . code_gen_buffer || tc_ptr >= ( uintptr_t ) tcg_ctx . code_gen_ptr ) { return NULL ; } m_min = 0 ; m_max = tcg_ctx . tb_ctx . nb_tbs - 1 ; while ( m_min <= m_max ) { m = ( m_min + m_max ) >> 1 ; tb = & tcg_ctx . tb_ctx . tbs [ m ] ; v = ( uintptr_t ) tb -> tc_ptr ; if ( v == tc_ptr ) { return tb ; } else if ( tc_ptr < v ) { m_max = m - 1 ; } else { m_min = m + 1 ; } } return & tcg_ctx . tb_ctx . tbs [ m_max ] ; }
1,432
1
int sequencer_write(int dev, struct file *file, const char __user *buf, int count) { unsigned char event_rec[EV_SZ], ev_code; int p = 0, c, ev_size; int mode = translate_mode(file); dev = dev >> 4; DEB(printk("sequencer_write(dev=%d, count=%d)\n", dev, count)); if (mode == OPEN_READ) return -EIO; c = count; while (c >= 4) { if (copy_from_user((char *) event_rec, &(buf)[p], 4)) goto out; ev_code = event_rec[0]; if (ev_code == SEQ_FULLSIZE) { int err, fmt; dev = *(unsigned short *) &event_rec[2]; if (dev < 0 || dev >= max_synthdev || synth_devs[dev] == NULL) return -ENXIO; if (!(synth_open_mask & (1 << dev))) return -ENXIO; fmt = (*(short *) &event_rec[0]) & 0xffff; err = synth_devs[dev]->load_patch(dev, fmt, buf, p + 4, c, 0); if (err < 0) return err; return err; } if (ev_code >= 128) { if (seq_mode == SEQ_2 && ev_code == SEQ_EXTENDED) { printk(KERN_WARNING "Sequencer: Invalid level 2 event %x\n", ev_code); return -EINVAL; } ev_size = 8; if (c < ev_size) { if (!seq_playing) seq_startplay(); return count - c; } if (copy_from_user((char *)&event_rec[4], &(buf)[p + 4], 4)) goto out; } else { if (seq_mode == SEQ_2) { printk(KERN_WARNING "Sequencer: 4 byte event in level 2 mode\n"); return -EINVAL; } ev_size = 4; if (event_rec[0] != SEQ_MIDIPUTC) obsolete_api_used = 1; } if (event_rec[0] == SEQ_MIDIPUTC) { if (!midi_opened[event_rec[2]]) { int err, mode; int dev = event_rec[2]; if (dev >= max_mididev || midi_devs[dev]==NULL) { /*printk("Sequencer Error: Nonexistent MIDI device %d\n", dev);*/ return -ENXIO; } mode = translate_mode(file); if ((err = midi_devs[dev]->open(dev, mode, sequencer_midi_input, sequencer_midi_output)) < 0) { seq_reset(); printk(KERN_WARNING "Sequencer Error: Unable to open Midi #%d\n", dev); return err; } midi_opened[dev] = 1; } } if (!seq_queue(event_rec, (file->f_flags & (O_NONBLOCK) ? 1 : 0))) { int processed = count - c; if (!seq_playing) seq_startplay(); if (!processed && (file->f_flags & O_NONBLOCK)) return -EAGAIN; else return processed; } p += ev_size; c -= ev_size; } if (!seq_playing) seq_startplay(); out: return count; }
int sequencer_write(int dev, struct file *file, const char __user *buf, int count) { unsigned char event_rec[EV_SZ], ev_code; int p = 0, c, ev_size; int mode = translate_mode(file); dev = dev >> 4; DEB(printk("sequencer_write(dev=%d, count=%d)\n", dev, count)); if (mode == OPEN_READ) return -EIO; c = count; while (c >= 4) { if (copy_from_user((char *) event_rec, &(buf)[p], 4)) goto out; ev_code = event_rec[0]; if (ev_code == SEQ_FULLSIZE) { int err, fmt; dev = *(unsigned short *) &event_rec[2]; if (dev < 0 || dev >= max_synthdev || synth_devs[dev] == NULL) return -ENXIO; if (!(synth_open_mask & (1 << dev))) return -ENXIO; fmt = (*(short *) &event_rec[0]) & 0xffff; err = synth_devs[dev]->load_patch(dev, fmt, buf, p + 4, c, 0); if (err < 0) return err; return err; } if (ev_code >= 128) { if (seq_mode == SEQ_2 && ev_code == SEQ_EXTENDED) { printk(KERN_WARNING "Sequencer: Invalid level 2 event %x\n", ev_code); return -EINVAL; } ev_size = 8; if (c < ev_size) { if (!seq_playing) seq_startplay(); return count - c; } if (copy_from_user((char *)&event_rec[4], &(buf)[p + 4], 4)) goto out; } else { if (seq_mode == SEQ_2) { printk(KERN_WARNING "Sequencer: 4 byte event in level 2 mode\n"); return -EINVAL; } ev_size = 4; if (event_rec[0] != SEQ_MIDIPUTC) obsolete_api_used = 1; } if (event_rec[0] == SEQ_MIDIPUTC) { if (!midi_opened[event_rec[2]]) { int err, mode; int dev = event_rec[2]; if (dev >= max_mididev || midi_devs[dev]==NULL) { return -ENXIO; } mode = translate_mode(file); if ((err = midi_devs[dev]->open(dev, mode, sequencer_midi_input, sequencer_midi_output)) < 0) { seq_reset(); printk(KERN_WARNING "Sequencer Error: Unable to open Midi #%d\n", dev); return err; } midi_opened[dev] = 1; } } if (!seq_queue(event_rec, (file->f_flags & (O_NONBLOCK) ? 1 : 0))) { int processed = count - c; if (!seq_playing) seq_startplay(); if (!processed && (file->f_flags & O_NONBLOCK)) return -EAGAIN; else return processed; } p += ev_size; c -= ev_size; } if (!seq_playing) seq_startplay(); out: return count; }
1,433
0
static int zrsdparams ( i_ctx_t * i_ctx_p ) { os_ptr op = osp ; ref * pFilter ; ref * pDecodeParms ; int Intent = 0 ; bool AsyncRead = false ; ref empty_array , filter1_array , parms1_array ; uint i ; int code = 0 ; if ( ref_stack_count ( & o_stack ) < 1 ) return_error ( gs_error_stackunderflow ) ; if ( ! r_has_type ( op , t_dictionary ) && ! r_has_type ( op , t_null ) ) { return_error ( gs_error_typecheck ) ; } make_empty_array ( & empty_array , a_readonly ) ; if ( r_has_type ( op , t_dictionary ) && dict_find_string ( op , "Filter" , & pFilter ) > 0 ) { if ( ! r_is_array ( pFilter ) ) { if ( ! r_has_type ( pFilter , t_name ) ) return_error ( gs_error_typecheck ) ; make_array ( & filter1_array , a_readonly , 1 , pFilter ) ; pFilter = & filter1_array ; } } else pFilter = & empty_array ; if ( pFilter != & empty_array && dict_find_string ( op , "DecodeParms" , & pDecodeParms ) > 0 ) { if ( pFilter == & filter1_array ) { make_array ( & parms1_array , a_readonly , 1 , pDecodeParms ) ; pDecodeParms = & parms1_array ; } else if ( ! r_is_array ( pDecodeParms ) ) return_error ( gs_error_typecheck ) ; else if ( r_size ( pFilter ) != r_size ( pDecodeParms ) ) return_error ( gs_error_rangecheck ) ; } else pDecodeParms = 0 ; for ( i = 0 ; i < r_size ( pFilter ) ; ++ i ) { ref f , fname , dp ; array_get ( imemory , pFilter , ( long ) i , & f ) ; if ( ! r_has_type ( & f , t_name ) ) return_error ( gs_error_typecheck ) ; name_string_ref ( imemory , & f , & fname ) ; if ( r_size ( & fname ) < 6 || memcmp ( fname . value . bytes + r_size ( & fname ) - 6 , "Decode" , 6 ) ) return_error ( gs_error_rangecheck ) ; if ( pDecodeParms ) { array_get ( imemory , pDecodeParms , ( long ) i , & dp ) ; if ( ! ( r_has_type ( & dp , t_dictionary ) || r_has_type ( & dp , t_null ) ) ) return_error ( gs_error_typecheck ) ; } } if ( r_has_type ( op , t_dictionary ) ) code = dict_int_param ( op , "Intent" , 0 , 3 , 0 , & Intent ) ; if ( code < 0 && code != gs_error_rangecheck ) return code ; if ( r_has_type ( op , t_dictionary ) ) if ( ( code = dict_bool_param ( op , "AsyncRead" , false , & AsyncRead ) ) < 0 ) return code ; push ( 1 ) ; op [ - 1 ] = * pFilter ; if ( pDecodeParms ) * op = * pDecodeParms ; else make_null ( op ) ; return 0 ; }
static int zrsdparams ( i_ctx_t * i_ctx_p ) { os_ptr op = osp ; ref * pFilter ; ref * pDecodeParms ; int Intent = 0 ; bool AsyncRead = false ; ref empty_array , filter1_array , parms1_array ; uint i ; int code = 0 ; if ( ref_stack_count ( & o_stack ) < 1 ) return_error ( gs_error_stackunderflow ) ; if ( ! r_has_type ( op , t_dictionary ) && ! r_has_type ( op , t_null ) ) { return_error ( gs_error_typecheck ) ; } make_empty_array ( & empty_array , a_readonly ) ; if ( r_has_type ( op , t_dictionary ) && dict_find_string ( op , "Filter" , & pFilter ) > 0 ) { if ( ! r_is_array ( pFilter ) ) { if ( ! r_has_type ( pFilter , t_name ) ) return_error ( gs_error_typecheck ) ; make_array ( & filter1_array , a_readonly , 1 , pFilter ) ; pFilter = & filter1_array ; } } else pFilter = & empty_array ; if ( pFilter != & empty_array && dict_find_string ( op , "DecodeParms" , & pDecodeParms ) > 0 ) { if ( pFilter == & filter1_array ) { make_array ( & parms1_array , a_readonly , 1 , pDecodeParms ) ; pDecodeParms = & parms1_array ; } else if ( ! r_is_array ( pDecodeParms ) ) return_error ( gs_error_typecheck ) ; else if ( r_size ( pFilter ) != r_size ( pDecodeParms ) ) return_error ( gs_error_rangecheck ) ; } else pDecodeParms = 0 ; for ( i = 0 ; i < r_size ( pFilter ) ; ++ i ) { ref f , fname , dp ; array_get ( imemory , pFilter , ( long ) i , & f ) ; if ( ! r_has_type ( & f , t_name ) ) return_error ( gs_error_typecheck ) ; name_string_ref ( imemory , & f , & fname ) ; if ( r_size ( & fname ) < 6 || memcmp ( fname . value . bytes + r_size ( & fname ) - 6 , "Decode" , 6 ) ) return_error ( gs_error_rangecheck ) ; if ( pDecodeParms ) { array_get ( imemory , pDecodeParms , ( long ) i , & dp ) ; if ( ! ( r_has_type ( & dp , t_dictionary ) || r_has_type ( & dp , t_null ) ) ) return_error ( gs_error_typecheck ) ; } } if ( r_has_type ( op , t_dictionary ) ) code = dict_int_param ( op , "Intent" , 0 , 3 , 0 , & Intent ) ; if ( code < 0 && code != gs_error_rangecheck ) return code ; if ( r_has_type ( op , t_dictionary ) ) if ( ( code = dict_bool_param ( op , "AsyncRead" , false , & AsyncRead ) ) < 0 ) return code ; push ( 1 ) ; op [ - 1 ] = * pFilter ; if ( pDecodeParms ) * op = * pDecodeParms ; else make_null ( op ) ; return 0 ; }
1,434
1
static int atalk_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sockaddr_at sat; struct sock *sk = sock->sk; struct atalk_sock *at = at_sk(sk); if (sock_flag(sk, SOCK_ZAPPED)) if (atalk_autobind(sk) < 0) return -ENOBUFS; *uaddr_len = sizeof(struct sockaddr_at); if (peer) { if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; sat.sat_addr.s_net = at->dest_net; sat.sat_addr.s_node = at->dest_node; sat.sat_port = at->dest_port; } else { sat.sat_addr.s_net = at->src_net; sat.sat_addr.s_node = at->src_node; sat.sat_port = at->src_port; } sat.sat_family = AF_APPLETALK; memcpy(uaddr, &sat, sizeof(sat)); return 0; }
static int atalk_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sockaddr_at sat; struct sock *sk = sock->sk; struct atalk_sock *at = at_sk(sk); if (sock_flag(sk, SOCK_ZAPPED)) if (atalk_autobind(sk) < 0) return -ENOBUFS; *uaddr_len = sizeof(struct sockaddr_at); if (peer) { if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; sat.sat_addr.s_net = at->dest_net; sat.sat_addr.s_node = at->dest_node; sat.sat_port = at->dest_port; } else { sat.sat_addr.s_net = at->src_net; sat.sat_addr.s_node = at->src_node; sat.sat_port = at->src_port; } sat.sat_family = AF_APPLETALK; memcpy(uaddr, &sat, sizeof(sat)); return 0; }
1,437
1
static int econet_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sock *sk; struct econet_sock *eo; struct sockaddr_ec *sec = (struct sockaddr_ec *)uaddr; if (peer) return -EOPNOTSUPP; mutex_lock(&econet_mutex); sk = sock->sk; eo = ec_sk(sk); sec->sec_family = AF_ECONET; sec->port = eo->port; sec->addr.station = eo->station; sec->addr.net = eo->net; mutex_unlock(&econet_mutex); *uaddr_len = sizeof(*sec); return 0; }
static int econet_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sock *sk; struct econet_sock *eo; struct sockaddr_ec *sec = (struct sockaddr_ec *)uaddr; if (peer) return -EOPNOTSUPP; mutex_lock(&econet_mutex); sk = sock->sk; eo = ec_sk(sk); sec->sec_family = AF_ECONET; sec->port = eo->port; sec->addr.station = eo->station; sec->addr.net = eo->net; mutex_unlock(&econet_mutex); *uaddr_len = sizeof(*sec); return 0; }
1,438
0
inline typename V::VariantType FBUnserializer<V>::unserialize( folly::StringPiece serialized) { FBUnserializer<V> unserializer(serialized); return unserializer.unserializeThing(0); }
inline typename V::VariantType FBUnserializer<V>::unserialize( folly::StringPiece serialized) { FBUnserializer<V> unserializer(serialized); return unserializer.unserializeThing(0); }
1,439
0
static ossl_inline t2 * sk_ ## t1 ## _delete ( STACK_OF ( t1 ) * sk , int i ) { return ( t2 * ) OPENSSL_sk_delete ( ( OPENSSL_STACK * ) sk , i ) ; } static ossl_inline t2 * sk_ ## t1 ## _delete_ptr ( STACK_OF ( t1 ) * sk , t2 * ptr ) { return ( t2 * ) OPENSSL_sk_delete_ptr ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr ) ; } static ossl_inline int sk_ ## t1 ## _push ( STACK_OF ( t1 ) * sk , t2 * ptr ) { return OPENSSL_sk_push ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr ) ; } static ossl_inline int sk_ ## t1 ## _unshift ( STACK_OF ( t1 ) * sk , t2 * ptr ) { return OPENSSL_sk_unshift ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr ) ; } static ossl_inline t2 * sk_ ## t1 ## _pop ( STACK_OF ( t1 ) * sk ) { return ( t2 * ) OPENSSL_sk_pop ( ( OPENSSL_STACK * ) sk ) ; } static ossl_inline t2 * sk_ ## t1 ## _shift ( STACK_OF ( t1 ) * sk ) { return ( t2 * ) OPENSSL_sk_shift ( ( OPENSSL_STACK * ) sk ) ; } static ossl_inline void sk_ ## t1 ## _pop_free ( STACK_OF ( t1 ) * sk , sk_ ## t1 ## _freefunc freefunc ) { OPENSSL_sk_pop_free ( ( OPENSSL_STACK * ) sk , ( OPENSSL_sk_freefunc ) freefunc ) ; } static ossl_inline int sk_ ## t1 ## _insert ( STACK_OF ( t1 ) * sk , t2 * ptr , int idx ) { return OPENSSL_sk_insert ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr , idx ) ; } static ossl_inline t2 * sk_ ## t1 ## _set ( STACK_OF ( t1 ) * sk , int idx , t2 * ptr ) { return ( t2 * ) OPENSSL_sk_set ( ( OPENSSL_STACK * ) sk , idx , ( const void * ) ptr ) ; } static ossl_inline int sk_ ## t1 ## _find ( STACK_OF ( t1 ) * sk , t2 * ptr ) { return OPENSSL_sk_find ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr ) ; } static ossl_inline int sk_ ## t1 ## _find_ex ( STACK_OF ( t1 ) * sk , t2 * ptr ) { return OPENSSL_sk_find_ex ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr ) ; } static ossl_inline void sk_ ## t1 ## _sort ( STACK_OF ( t1 ) * sk ) { OPENSSL_sk_sort ( ( OPENSSL_STACK * ) sk ) ; } static ossl_inline int sk_ ## t1 ## _is_sorted ( const STACK_OF ( t1 ) * sk ) { return OPENSSL_sk_is_sorted ( ( const OPENSSL_STACK * ) sk ) ; } static ossl_inline STACK_OF ( t1 ) * sk_ ## t1 ## _dup ( const STACK_OF ( t1 ) * sk ) { return ( STACK_OF ( t1 ) * ) OPENSSL_sk_dup ( ( const OPENSSL_STACK * ) sk ) ; } static ossl_inline STACK_OF ( t1 ) * sk_ ## t1 ## _deep_copy ( const STACK_OF ( t1 ) * sk , sk_ ## t1 ## _copyfunc copyfunc , sk_ ## t1 ## _freefunc freefunc ) { return ( STACK_OF ( t1 ) * ) OPENSSL_sk_deep_copy ( ( const OPENSSL_STACK * ) sk , ( OPENSSL_sk_copyfunc ) copyfunc , ( OPENSSL_sk_freefunc ) freefunc ) ; } static ossl_inline sk_ ## t1 ## _compfunc sk_ ## t1 ## _set_cmp_func ( STACK_OF ( t1 ) * sk , sk_ ## t1 ## _compfunc compare ) { return ( sk_ ## t1 ## _compfunc ) OPENSSL_sk_set_cmp_func ( ( OPENSSL_STACK * ) sk , ( OPENSSL_sk_compfunc ) compare ) ; } # define DEFINE_SPECIAL_STACK_OF ( t1 , t2 ) SKM_DEFINE_STACK_OF ( t1 , t2 , t2 ) # define DEFINE_STACK_OF ( t ) SKM_DEFINE_STACK_OF ( t , t , t ) # define DEFINE_SPECIAL_STACK_OF_CONST ( t1 , t2 ) SKM_DEFINE_STACK_OF ( t1 , const t2 , t2 ) # define DEFINE_STACK_OF_CONST ( t ) SKM_DEFINE_STACK_OF ( t , const t , t ) typedef char * OPENSSL_STRING ; typedef const char * OPENSSL_CSTRING ; DEFINE_SPECIAL_STACK_OF ( OPENSSL_STRING , char )
static ossl_inline t2 * sk_ ## t1 ## _delete ( STACK_OF ( t1 ) * sk , int i ) { return ( t2 * ) OPENSSL_sk_delete ( ( OPENSSL_STACK * ) sk , i ) ; } static ossl_inline t2 * sk_ ## t1 ## _delete_ptr ( STACK_OF ( t1 ) * sk , t2 * ptr ) { return ( t2 * ) OPENSSL_sk_delete_ptr ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr ) ; } static ossl_inline int sk_ ## t1 ## _push ( STACK_OF ( t1 ) * sk , t2 * ptr ) { return OPENSSL_sk_push ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr ) ; } static ossl_inline int sk_ ## t1 ## _unshift ( STACK_OF ( t1 ) * sk , t2 * ptr ) { return OPENSSL_sk_unshift ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr ) ; } static ossl_inline t2 * sk_ ## t1 ## _pop ( STACK_OF ( t1 ) * sk ) { return ( t2 * ) OPENSSL_sk_pop ( ( OPENSSL_STACK * ) sk ) ; } static ossl_inline t2 * sk_ ## t1 ## _shift ( STACK_OF ( t1 ) * sk ) { return ( t2 * ) OPENSSL_sk_shift ( ( OPENSSL_STACK * ) sk ) ; } static ossl_inline void sk_ ## t1 ## _pop_free ( STACK_OF ( t1 ) * sk , sk_ ## t1 ## _freefunc freefunc ) { OPENSSL_sk_pop_free ( ( OPENSSL_STACK * ) sk , ( OPENSSL_sk_freefunc ) freefunc ) ; } static ossl_inline int sk_ ## t1 ## _insert ( STACK_OF ( t1 ) * sk , t2 * ptr , int idx ) { return OPENSSL_sk_insert ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr , idx ) ; } static ossl_inline t2 * sk_ ## t1 ## _set ( STACK_OF ( t1 ) * sk , int idx , t2 * ptr ) { return ( t2 * ) OPENSSL_sk_set ( ( OPENSSL_STACK * ) sk , idx , ( const void * ) ptr ) ; } static ossl_inline int sk_ ## t1 ## _find ( STACK_OF ( t1 ) * sk , t2 * ptr ) { return OPENSSL_sk_find ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr ) ; } static ossl_inline int sk_ ## t1 ## _find_ex ( STACK_OF ( t1 ) * sk , t2 * ptr ) { return OPENSSL_sk_find_ex ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr ) ; } static ossl_inline void sk_ ## t1 ## _sort ( STACK_OF ( t1 ) * sk ) { OPENSSL_sk_sort ( ( OPENSSL_STACK * ) sk ) ; } static ossl_inline int sk_ ## t1 ## _is_sorted ( const STACK_OF ( t1 ) * sk ) { return OPENSSL_sk_is_sorted ( ( const OPENSSL_STACK * ) sk ) ; } static ossl_inline STACK_OF ( t1 ) * sk_ ## t1 ## _dup ( const STACK_OF ( t1 ) * sk ) { return ( STACK_OF ( t1 ) * ) OPENSSL_sk_dup ( ( const OPENSSL_STACK * ) sk ) ; } static ossl_inline STACK_OF ( t1 ) * sk_ ## t1 ## _deep_copy ( const STACK_OF ( t1 ) * sk , sk_ ## t1 ## _copyfunc copyfunc , sk_ ## t1 ## _freefunc freefunc ) { return ( STACK_OF ( t1 ) * ) OPENSSL_sk_deep_copy ( ( const OPENSSL_STACK * ) sk , ( OPENSSL_sk_copyfunc ) copyfunc , ( OPENSSL_sk_freefunc ) freefunc ) ; } static ossl_inline sk_ ## t1 ## _compfunc sk_ ## t1 ## _set_cmp_func ( STACK_OF ( t1 ) * sk , sk_ ## t1 ## _compfunc compare ) { return ( sk_ ## t1 ## _compfunc ) OPENSSL_sk_set_cmp_func ( ( OPENSSL_STACK * ) sk , ( OPENSSL_sk_compfunc ) compare ) ; } # define DEFINE_SPECIAL_STACK_OF ( t1 , t2 ) SKM_DEFINE_STACK_OF ( t1 , t2 , t2 ) # define DEFINE_STACK_OF ( t ) SKM_DEFINE_STACK_OF ( t , t , t ) # define DEFINE_SPECIAL_STACK_OF_CONST ( t1 , t2 ) SKM_DEFINE_STACK_OF ( t1 , const t2 , t2 ) # define DEFINE_STACK_OF_CONST ( t ) SKM_DEFINE_STACK_OF ( t , const t , t ) typedef char * OPENSSL_STRING ; typedef const char * OPENSSL_CSTRING ; DEFINE_SPECIAL_STACK_OF ( OPENSSL_STRING , char )
1,441
1
static int raw_getname(struct socket *sock, struct sockaddr *uaddr, int *len, int peer) { struct sockaddr_can *addr = (struct sockaddr_can *)uaddr; struct sock *sk = sock->sk; struct raw_sock *ro = raw_sk(sk); if (peer) return -EOPNOTSUPP; addr->can_family = AF_CAN; addr->can_ifindex = ro->ifindex; *len = sizeof(*addr); return 0; }
static int raw_getname(struct socket *sock, struct sockaddr *uaddr, int *len, int peer) { struct sockaddr_can *addr = (struct sockaddr_can *)uaddr; struct sock *sk = sock->sk; struct raw_sock *ro = raw_sk(sk); if (peer) return -EOPNOTSUPP; addr->can_family = AF_CAN; addr->can_ifindex = ro->ifindex; *len = sizeof(*addr); return 0; }
1,443
0
inline typename V::VectorType FBUnserializer<V>::unserializeList(size_t depth) { p_ += CODE_SIZE; // the list size is written so we can reserve it in the vector // in future. Skip past it for now. unserializeInt64(); typename V::VectorType ret = V::createVector(); size_t code = nextCode(); while (code != FB_SERIALIZE_STOP) { V::vectorAppend(ret, unserializeThing(depth + 1)); code = nextCode(); } p_ += CODE_SIZE; return ret; }
inline typename V::VectorType FBUnserializer<V>::unserializeList(size_t depth) { p_ += CODE_SIZE; unserializeInt64(); typename V::VectorType ret = V::createVector(); size_t code = nextCode(); while (code != FB_SERIALIZE_STOP) { V::vectorAppend(ret, unserializeThing(depth + 1)); code = nextCode(); } p_ += CODE_SIZE; return ret; }
1,445
0
static int collector_decode_htmlnumericentity ( int c , void * data ) { struct collector_htmlnumericentity_data * pc = ( struct collector_htmlnumericentity_data * ) data ; int f , n , s , r , d , size , * mapelm ; switch ( pc -> status ) { case 1 : if ( c == 0x23 ) { pc -> status = 2 ; } else { pc -> status = 0 ; ( * pc -> decoder -> filter_function ) ( 0x26 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( c , pc -> decoder ) ; } break ; case 2 : if ( c == 0x78 ) { pc -> status = 4 ; } else if ( c >= 0x30 && c <= 0x39 ) { pc -> cache = c - 0x30 ; pc -> status = 3 ; pc -> digit = 1 ; } else { pc -> status = 0 ; ( * pc -> decoder -> filter_function ) ( 0x26 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( 0x23 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( c , pc -> decoder ) ; } break ; case 3 : s = 0 ; f = 0 ; if ( c >= 0x30 && c <= 0x39 ) { if ( pc -> digit > 9 ) { pc -> status = 0 ; s = pc -> cache ; f = 1 ; } else { s = pc -> cache * 10 + c - 0x30 ; pc -> cache = s ; pc -> digit ++ ; } } else { pc -> status = 0 ; s = pc -> cache ; f = 1 ; n = 0 ; size = pc -> mapsize ; while ( n < size ) { mapelm = & ( pc -> convmap [ n * 4 ] ) ; d = s - mapelm [ 2 ] ; if ( d >= mapelm [ 0 ] && d <= mapelm [ 1 ] ) { f = 0 ; ( * pc -> decoder -> filter_function ) ( d , pc -> decoder ) ; if ( c != 0x3b ) { ( * pc -> decoder -> filter_function ) ( c , pc -> decoder ) ; } break ; } n ++ ; } } if ( f ) { ( * pc -> decoder -> filter_function ) ( 0x26 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( 0x23 , pc -> decoder ) ; r = 1 ; n = pc -> digit ; while ( n > 0 ) { r *= 10 ; n -- ; } s %= r ; r /= 10 ; while ( r > 0 ) { d = s / r ; s %= r ; r /= 10 ; ( * pc -> decoder -> filter_function ) ( mbfl_hexchar_table [ d ] , pc -> decoder ) ; } ( * pc -> decoder -> filter_function ) ( c , pc -> decoder ) ; } break ; case 4 : if ( c >= 0x30 && c <= 0x39 ) { pc -> cache = c - 0x30 ; pc -> status = 5 ; pc -> digit = 1 ; } else if ( c >= 0x41 && c <= 0x46 ) { pc -> cache = c - 0x41 + 10 ; pc -> status = 5 ; pc -> digit = 1 ; } else if ( c >= 0x61 && c <= 0x66 ) { pc -> cache = c - 0x61 + 10 ; pc -> status = 5 ; pc -> digit = 1 ; } else { pc -> status = 0 ; ( * pc -> decoder -> filter_function ) ( 0x26 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( 0x23 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( 0x78 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( c , pc -> decoder ) ; } break ; case 5 : s = 0 ; f = 0 ; if ( ( c >= 0x30 && c <= 0x39 ) || ( c >= 0x41 && c <= 0x46 ) || ( c >= 0x61 && c <= 0x66 ) ) { if ( pc -> digit > 9 ) { pc -> status = 0 ; s = pc -> cache ; f = 1 ; } else { if ( c >= 0x30 && c <= 0x39 ) { s = pc -> cache * 16 + ( c - 0x30 ) ; } else if ( c >= 0x41 && c <= 0x46 ) { s = pc -> cache * 16 + ( c - 0x41 + 10 ) ; } else { s = pc -> cache * 16 + ( c - 0x61 + 10 ) ; } pc -> cache = s ; pc -> digit ++ ; } } else { pc -> status = 0 ; s = pc -> cache ; f = 1 ; n = 0 ; size = pc -> mapsize ; while ( n < size ) { mapelm = & ( pc -> convmap [ n * 4 ] ) ; d = s - mapelm [ 2 ] ; if ( d >= mapelm [ 0 ] && d <= mapelm [ 1 ] ) { f = 0 ; ( * pc -> decoder -> filter_function ) ( d , pc -> decoder ) ; if ( c != 0x3b ) { ( * pc -> decoder -> filter_function ) ( c , pc -> decoder ) ; } break ; } n ++ ; } } if ( f ) { ( * pc -> decoder -> filter_function ) ( 0x26 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( 0x23 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( 0x78 , pc -> decoder ) ; r = 1 ; n = pc -> digit ; while ( n > 0 ) { r *= 16 ; n -- ; } s %= r ; r /= 16 ; while ( r > 0 ) { d = s / r ; s %= r ; r /= 16 ; ( * pc -> decoder -> filter_function ) ( mbfl_hexchar_table [ d ] , pc -> decoder ) ; } ( * pc -> decoder -> filter_function ) ( c , pc -> decoder ) ; } break ; default : if ( c == 0x26 ) { pc -> status = 1 ; } else { ( * pc -> decoder -> filter_function ) ( c , pc -> decoder ) ; } break ; } return c ; }
static int collector_decode_htmlnumericentity ( int c , void * data ) { struct collector_htmlnumericentity_data * pc = ( struct collector_htmlnumericentity_data * ) data ; int f , n , s , r , d , size , * mapelm ; switch ( pc -> status ) { case 1 : if ( c == 0x23 ) { pc -> status = 2 ; } else { pc -> status = 0 ; ( * pc -> decoder -> filter_function ) ( 0x26 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( c , pc -> decoder ) ; } break ; case 2 : if ( c == 0x78 ) { pc -> status = 4 ; } else if ( c >= 0x30 && c <= 0x39 ) { pc -> cache = c - 0x30 ; pc -> status = 3 ; pc -> digit = 1 ; } else { pc -> status = 0 ; ( * pc -> decoder -> filter_function ) ( 0x26 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( 0x23 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( c , pc -> decoder ) ; } break ; case 3 : s = 0 ; f = 0 ; if ( c >= 0x30 && c <= 0x39 ) { if ( pc -> digit > 9 ) { pc -> status = 0 ; s = pc -> cache ; f = 1 ; } else { s = pc -> cache * 10 + c - 0x30 ; pc -> cache = s ; pc -> digit ++ ; } } else { pc -> status = 0 ; s = pc -> cache ; f = 1 ; n = 0 ; size = pc -> mapsize ; while ( n < size ) { mapelm = & ( pc -> convmap [ n * 4 ] ) ; d = s - mapelm [ 2 ] ; if ( d >= mapelm [ 0 ] && d <= mapelm [ 1 ] ) { f = 0 ; ( * pc -> decoder -> filter_function ) ( d , pc -> decoder ) ; if ( c != 0x3b ) { ( * pc -> decoder -> filter_function ) ( c , pc -> decoder ) ; } break ; } n ++ ; } } if ( f ) { ( * pc -> decoder -> filter_function ) ( 0x26 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( 0x23 , pc -> decoder ) ; r = 1 ; n = pc -> digit ; while ( n > 0 ) { r *= 10 ; n -- ; } s %= r ; r /= 10 ; while ( r > 0 ) { d = s / r ; s %= r ; r /= 10 ; ( * pc -> decoder -> filter_function ) ( mbfl_hexchar_table [ d ] , pc -> decoder ) ; } ( * pc -> decoder -> filter_function ) ( c , pc -> decoder ) ; } break ; case 4 : if ( c >= 0x30 && c <= 0x39 ) { pc -> cache = c - 0x30 ; pc -> status = 5 ; pc -> digit = 1 ; } else if ( c >= 0x41 && c <= 0x46 ) { pc -> cache = c - 0x41 + 10 ; pc -> status = 5 ; pc -> digit = 1 ; } else if ( c >= 0x61 && c <= 0x66 ) { pc -> cache = c - 0x61 + 10 ; pc -> status = 5 ; pc -> digit = 1 ; } else { pc -> status = 0 ; ( * pc -> decoder -> filter_function ) ( 0x26 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( 0x23 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( 0x78 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( c , pc -> decoder ) ; } break ; case 5 : s = 0 ; f = 0 ; if ( ( c >= 0x30 && c <= 0x39 ) || ( c >= 0x41 && c <= 0x46 ) || ( c >= 0x61 && c <= 0x66 ) ) { if ( pc -> digit > 9 ) { pc -> status = 0 ; s = pc -> cache ; f = 1 ; } else { if ( c >= 0x30 && c <= 0x39 ) { s = pc -> cache * 16 + ( c - 0x30 ) ; } else if ( c >= 0x41 && c <= 0x46 ) { s = pc -> cache * 16 + ( c - 0x41 + 10 ) ; } else { s = pc -> cache * 16 + ( c - 0x61 + 10 ) ; } pc -> cache = s ; pc -> digit ++ ; } } else { pc -> status = 0 ; s = pc -> cache ; f = 1 ; n = 0 ; size = pc -> mapsize ; while ( n < size ) { mapelm = & ( pc -> convmap [ n * 4 ] ) ; d = s - mapelm [ 2 ] ; if ( d >= mapelm [ 0 ] && d <= mapelm [ 1 ] ) { f = 0 ; ( * pc -> decoder -> filter_function ) ( d , pc -> decoder ) ; if ( c != 0x3b ) { ( * pc -> decoder -> filter_function ) ( c , pc -> decoder ) ; } break ; } n ++ ; } } if ( f ) { ( * pc -> decoder -> filter_function ) ( 0x26 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( 0x23 , pc -> decoder ) ; ( * pc -> decoder -> filter_function ) ( 0x78 , pc -> decoder ) ; r = 1 ; n = pc -> digit ; while ( n > 0 ) { r *= 16 ; n -- ; } s %= r ; r /= 16 ; while ( r > 0 ) { d = s / r ; s %= r ; r /= 16 ; ( * pc -> decoder -> filter_function ) ( mbfl_hexchar_table [ d ] , pc -> decoder ) ; } ( * pc -> decoder -> filter_function ) ( c , pc -> decoder ) ; } break ; default : if ( c == 0x26 ) { pc -> status = 1 ; } else { ( * pc -> decoder -> filter_function ) ( c , pc -> decoder ) ; } break ; } return c ; }
1,446
1
inline typename V::VectorType FBUnserializer<V>::unserializeList() { p_ += CODE_SIZE; // the list size is written so we can reserve it in the vector // in future. Skip past it for now. unserializeInt64(); typename V::VectorType ret = V::createVector(); size_t code = nextCode(); while (code != FB_SERIALIZE_STOP) { V::vectorAppend(ret, unserializeThing()); code = nextCode(); } p_ += CODE_SIZE; return ret; }
inline typename V::VectorType FBUnserializer<V>::unserializeList() { p_ += CODE_SIZE; unserializeInt64(); typename V::VectorType ret = V::createVector(); size_t code = nextCode(); while (code != FB_SERIALIZE_STOP) { V::vectorAppend(ret, unserializeThing()); code = nextCode(); } p_ += CODE_SIZE; return ret; }
1,447
1
static int nr_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct full_sockaddr_ax25 *sax = (struct full_sockaddr_ax25 *)uaddr; struct sock *sk = sock->sk; struct nr_sock *nr = nr_sk(sk); lock_sock(sk); if (peer != 0) { if (sk->sk_state != TCP_ESTABLISHED) { release_sock(sk); return -ENOTCONN; } sax->fsa_ax25.sax25_family = AF_NETROM; sax->fsa_ax25.sax25_ndigis = 1; sax->fsa_ax25.sax25_call = nr->user_addr; sax->fsa_digipeater[0] = nr->dest_addr; *uaddr_len = sizeof(struct full_sockaddr_ax25); } else { sax->fsa_ax25.sax25_family = AF_NETROM; sax->fsa_ax25.sax25_ndigis = 0; sax->fsa_ax25.sax25_call = nr->source_addr; *uaddr_len = sizeof(struct sockaddr_ax25); } release_sock(sk); return 0; }
static int nr_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct full_sockaddr_ax25 *sax = (struct full_sockaddr_ax25 *)uaddr; struct sock *sk = sock->sk; struct nr_sock *nr = nr_sk(sk); lock_sock(sk); if (peer != 0) { if (sk->sk_state != TCP_ESTABLISHED) { release_sock(sk); return -ENOTCONN; } sax->fsa_ax25.sax25_family = AF_NETROM; sax->fsa_ax25.sax25_ndigis = 1; sax->fsa_ax25.sax25_call = nr->user_addr; sax->fsa_digipeater[0] = nr->dest_addr; *uaddr_len = sizeof(struct full_sockaddr_ax25); } else { sax->fsa_ax25.sax25_family = AF_NETROM; sax->fsa_ax25.sax25_ndigis = 0; sax->fsa_ax25.sax25_call = nr->source_addr; *uaddr_len = sizeof(struct sockaddr_ax25); } release_sock(sk); return 0; }
1,448
0
static int decode_exponents(AC3DecodeContext *ctx) { ac3_audio_block *ab = &ctx->audio_block; int i; uint8_t *exps; uint8_t *dexps; if (ab->flags & AC3_AB_CPLINU && ab->cplexpstr != AC3_EXPSTR_REUSE) if (_decode_exponents(ab->cplexpstr, ab->ncplgrps, ab->cplabsexp, ab->cplexps, ab->dcplexps + ab->cplstrtmant)) return -1; for (i = 0; i < ctx->bsi.nfchans; i++) if (ab->chexpstr[i] != AC3_EXPSTR_REUSE) { exps = ab->exps[i]; dexps = ab->dexps[i]; if (_decode_exponents(ab->chexpstr[i], ab->nchgrps[i], exps[0], exps + 1, dexps + 1)) return -1; } if (ctx->bsi.flags & AC3_BSI_LFEON && ab->lfeexpstr != AC3_EXPSTR_REUSE) if (_decode_exponents(ab->lfeexpstr, 2, ab->lfeexps[0], ab->lfeexps + 1, ab->dlfeexps)) return -1; return 0; }
static int decode_exponents(AC3DecodeContext *ctx) { ac3_audio_block *ab = &ctx->audio_block; int i; uint8_t *exps; uint8_t *dexps; if (ab->flags & AC3_AB_CPLINU && ab->cplexpstr != AC3_EXPSTR_REUSE) if (_decode_exponents(ab->cplexpstr, ab->ncplgrps, ab->cplabsexp, ab->cplexps, ab->dcplexps + ab->cplstrtmant)) return -1; for (i = 0; i < ctx->bsi.nfchans; i++) if (ab->chexpstr[i] != AC3_EXPSTR_REUSE) { exps = ab->exps[i]; dexps = ab->dexps[i]; if (_decode_exponents(ab->chexpstr[i], ab->nchgrps[i], exps[0], exps + 1, dexps + 1)) return -1; } if (ctx->bsi.flags & AC3_BSI_LFEON && ab->lfeexpstr != AC3_EXPSTR_REUSE) if (_decode_exponents(ab->lfeexpstr, 2, ab->lfeexps[0], ab->lfeexps + 1, ab->dlfeexps)) return -1; return 0; }
1,450
0
inline typename V::MapType FBUnserializer<V>::unserializeMap(size_t depth) { p_ += CODE_SIZE; typename V::MapType ret = V::createMap(); size_t code = nextCode(); while (code != FB_SERIALIZE_STOP) { switch (code) { case FB_SERIALIZE_VARCHAR: case FB_SERIALIZE_STRING: { auto key = unserializeString(); auto value = unserializeThing(depth + 1); V::mapSet(ret, std::move(key), std::move(value)); } break; default: { auto key = unserializeInt64(); auto value = unserializeThing(depth + 1); V::mapSet(ret, std::move(key), std::move(value)); } } code = nextCode(); } p_ += CODE_SIZE; return ret; }
inline typename V::MapType FBUnserializer<V>::unserializeMap(size_t depth) { p_ += CODE_SIZE; typename V::MapType ret = V::createMap(); size_t code = nextCode(); while (code != FB_SERIALIZE_STOP) { switch (code) { case FB_SERIALIZE_VARCHAR: case FB_SERIALIZE_STRING: { auto key = unserializeString(); auto value = unserializeThing(depth + 1); V::mapSet(ret, std::move(key), std::move(value)); } break; default: { auto key = unserializeInt64(); auto value = unserializeThing(depth + 1); V::mapSet(ret, std::move(key), std::move(value)); } } code = nextCode(); } p_ += CODE_SIZE; return ret; }
1,451
0
static unsigned long sun4m_load_kernel ( const char * kernel_filename , const char * initrd_filename , ram_addr_t RAM_size ) { int linux_boot ; unsigned int i ; long initrd_size , kernel_size ; uint8_t * ptr ; linux_boot = ( kernel_filename != NULL ) ; kernel_size = 0 ; if ( linux_boot ) { int bswap_needed ; # ifdef BSWAP_NEEDED bswap_needed = 1 ; # else bswap_needed = 0 ; # endif kernel_size = load_elf ( kernel_filename , translate_kernel_address , NULL , NULL , NULL , NULL , 1 , ELF_MACHINE , 0 ) ; if ( kernel_size < 0 ) kernel_size = load_aout ( kernel_filename , KERNEL_LOAD_ADDR , RAM_size - KERNEL_LOAD_ADDR , bswap_needed , TARGET_PAGE_SIZE ) ; if ( kernel_size < 0 ) kernel_size = load_image_targphys ( kernel_filename , KERNEL_LOAD_ADDR , RAM_size - KERNEL_LOAD_ADDR ) ; if ( kernel_size < 0 ) { fprintf ( stderr , "qemu: could not load kernel '%s'\n" , kernel_filename ) ; exit ( 1 ) ; } initrd_size = 0 ; if ( initrd_filename ) { initrd_size = load_image_targphys ( initrd_filename , INITRD_LOAD_ADDR , RAM_size - INITRD_LOAD_ADDR ) ; if ( initrd_size < 0 ) { fprintf ( stderr , "qemu: could not load initial ram disk '%s'\n" , initrd_filename ) ; exit ( 1 ) ; } } if ( initrd_size > 0 ) { for ( i = 0 ; i < 64 * TARGET_PAGE_SIZE ; i += TARGET_PAGE_SIZE ) { ptr = rom_ptr ( KERNEL_LOAD_ADDR + i ) ; if ( ldl_p ( ptr ) == 0x48647253 ) { stl_p ( ptr + 16 , INITRD_LOAD_ADDR ) ; stl_p ( ptr + 20 , initrd_size ) ; break ; } } } } return kernel_size ; }
static unsigned long sun4m_load_kernel ( const char * kernel_filename , const char * initrd_filename , ram_addr_t RAM_size ) { int linux_boot ; unsigned int i ; long initrd_size , kernel_size ; uint8_t * ptr ; linux_boot = ( kernel_filename != NULL ) ; kernel_size = 0 ; if ( linux_boot ) { int bswap_needed ; # ifdef BSWAP_NEEDED bswap_needed = 1 ; # else bswap_needed = 0 ; # endif kernel_size = load_elf ( kernel_filename , translate_kernel_address , NULL , NULL , NULL , NULL , 1 , ELF_MACHINE , 0 ) ; if ( kernel_size < 0 ) kernel_size = load_aout ( kernel_filename , KERNEL_LOAD_ADDR , RAM_size - KERNEL_LOAD_ADDR , bswap_needed , TARGET_PAGE_SIZE ) ; if ( kernel_size < 0 ) kernel_size = load_image_targphys ( kernel_filename , KERNEL_LOAD_ADDR , RAM_size - KERNEL_LOAD_ADDR ) ; if ( kernel_size < 0 ) { fprintf ( stderr , "qemu: could not load kernel '%s'\n" , kernel_filename ) ; exit ( 1 ) ; } initrd_size = 0 ; if ( initrd_filename ) { initrd_size = load_image_targphys ( initrd_filename , INITRD_LOAD_ADDR , RAM_size - INITRD_LOAD_ADDR ) ; if ( initrd_size < 0 ) { fprintf ( stderr , "qemu: could not load initial ram disk '%s'\n" , initrd_filename ) ; exit ( 1 ) ; } } if ( initrd_size > 0 ) { for ( i = 0 ; i < 64 * TARGET_PAGE_SIZE ; i += TARGET_PAGE_SIZE ) { ptr = rom_ptr ( KERNEL_LOAD_ADDR + i ) ; if ( ldl_p ( ptr ) == 0x48647253 ) { stl_p ( ptr + 16 , INITRD_LOAD_ADDR ) ; stl_p ( ptr + 20 , initrd_size ) ; break ; } } } } return kernel_size ; }
1,453
1
static int tc_fill_tclass(struct sk_buff *skb, struct Qdisc *q, unsigned long cl, u32 pid, u32 seq, u16 flags, int event) { struct tcmsg *tcm; struct nlmsghdr *nlh; unsigned char *b = skb_tail_pointer(skb); struct gnet_dump d; const struct Qdisc_class_ops *cl_ops = q->ops->cl_ops; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*tcm), flags); tcm = NLMSG_DATA(nlh); tcm->tcm_family = AF_UNSPEC; tcm->tcm_ifindex = qdisc_dev(q)->ifindex; tcm->tcm_parent = q->handle; tcm->tcm_handle = q->handle; tcm->tcm_info = 0; NLA_PUT_STRING(skb, TCA_KIND, q->ops->id); if (cl_ops->dump && cl_ops->dump(q, cl, skb, tcm) < 0) goto nla_put_failure; if (gnet_stats_start_copy_compat(skb, TCA_STATS2, TCA_STATS, TCA_XSTATS, qdisc_root_sleeping_lock(q), &d) < 0) goto nla_put_failure; if (cl_ops->dump_stats && cl_ops->dump_stats(q, cl, &d) < 0) goto nla_put_failure; if (gnet_stats_finish_copy(&d) < 0) goto nla_put_failure; nlh->nlmsg_len = skb_tail_pointer(skb) - b; return skb->len; nlmsg_failure: nla_put_failure: nlmsg_trim(skb, b); return -1; }
static int tc_fill_tclass(struct sk_buff *skb, struct Qdisc *q, unsigned long cl, u32 pid, u32 seq, u16 flags, int event) { struct tcmsg *tcm; struct nlmsghdr *nlh; unsigned char *b = skb_tail_pointer(skb); struct gnet_dump d; const struct Qdisc_class_ops *cl_ops = q->ops->cl_ops; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*tcm), flags); tcm = NLMSG_DATA(nlh); tcm->tcm_family = AF_UNSPEC; tcm->tcm_ifindex = qdisc_dev(q)->ifindex; tcm->tcm_parent = q->handle; tcm->tcm_handle = q->handle; tcm->tcm_info = 0; NLA_PUT_STRING(skb, TCA_KIND, q->ops->id); if (cl_ops->dump && cl_ops->dump(q, cl, skb, tcm) < 0) goto nla_put_failure; if (gnet_stats_start_copy_compat(skb, TCA_STATS2, TCA_STATS, TCA_XSTATS, qdisc_root_sleeping_lock(q), &d) < 0) goto nla_put_failure; if (cl_ops->dump_stats && cl_ops->dump_stats(q, cl, &d) < 0) goto nla_put_failure; if (gnet_stats_finish_copy(&d) < 0) goto nla_put_failure; nlh->nlmsg_len = skb_tail_pointer(skb) - b; return skb->len; nlmsg_failure: nla_put_failure: nlmsg_trim(skb, b); return -1; }
1,454
1
inline typename V::MapType FBUnserializer<V>::unserializeMap() { p_ += CODE_SIZE; typename V::MapType ret = V::createMap(); size_t code = nextCode(); while (code != FB_SERIALIZE_STOP) { switch (code) { case FB_SERIALIZE_VARCHAR: case FB_SERIALIZE_STRING: { auto key = unserializeString(); auto value = unserializeThing(); V::mapSet(ret, std::move(key), std::move(value)); } break; default: { auto key = unserializeInt64(); auto value = unserializeThing(); V::mapSet(ret, std::move(key), std::move(value)); } } code = nextCode(); } p_ += CODE_SIZE; return ret; }
inline typename V::MapType FBUnserializer<V>::unserializeMap() { p_ += CODE_SIZE; typename V::MapType ret = V::createMap(); size_t code = nextCode(); while (code != FB_SERIALIZE_STOP) { switch (code) { case FB_SERIALIZE_VARCHAR: case FB_SERIALIZE_STRING: { auto key = unserializeString(); auto value = unserializeThing(); V::mapSet(ret, std::move(key), std::move(value)); } break; default: { auto key = unserializeInt64(); auto value = unserializeThing(); V::mapSet(ret, std::move(key), std::move(value)); } } code = nextCode(); } p_ += CODE_SIZE; return ret; }
1,455
0
static int rose_parse_ccitt(unsigned char *p, struct rose_facilities_struct *facilities, int len) { unsigned char l, n = 0; char callsign[11]; do { switch (*p & 0xC0) { case 0x00: p += 2; n += 2; len -= 2; break; case 0x40: p += 3; n += 3; len -= 3; break; case 0x80: p += 4; n += 4; len -= 4; break; case 0xC0: l = p[1]; /* Prevent overflows*/ if (l < 10 || l > 20) return -1; if (*p == FAC_CCITT_DEST_NSAP) { memcpy(&facilities->source_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\0'; asc2ax(&facilities->source_call, callsign); } if (*p == FAC_CCITT_SRC_NSAP) { memcpy(&facilities->dest_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\0'; asc2ax(&facilities->dest_call, callsign); } p += l + 2; n += l + 2; len -= l + 2; break; } } while (*p != 0x00 && len > 0); return n; }
static int rose_parse_ccitt(unsigned char *p, struct rose_facilities_struct *facilities, int len) { unsigned char l, n = 0; char callsign[11]; do { switch (*p & 0xC0) { case 0x00: p += 2; n += 2; len -= 2; break; case 0x40: p += 3; n += 3; len -= 3; break; case 0x80: p += 4; n += 4; len -= 4; break; case 0xC0: l = p[1]; if (l < 10 || l > 20) return -1; if (*p == FAC_CCITT_DEST_NSAP) { memcpy(&facilities->source_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\0'; asc2ax(&facilities->source_call, callsign); } if (*p == FAC_CCITT_SRC_NSAP) { memcpy(&facilities->dest_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\0'; asc2ax(&facilities->dest_call, callsign); } p += l + 2; n += l + 2; len -= l + 2; break; } } while (*p != 0x00 && len > 0); return n; }
1,456
1
static __inline__ int cbq_dump_ovl(struct sk_buff *skb, struct cbq_class *cl) { unsigned char *b = skb->tail; struct tc_cbq_ovl opt; opt.strategy = cl->ovl_strategy; opt.priority2 = cl->priority2+1; opt.penalty = (cl->penalty*1000)/HZ; RTA_PUT(skb, TCA_CBQ_OVL_STRATEGY, sizeof(opt), &opt); return skb->len; rtattr_failure: skb_trim(skb, b - skb->data); return -1; }
static __inline__ int cbq_dump_ovl(struct sk_buff *skb, struct cbq_class *cl) { unsigned char *b = skb->tail; struct tc_cbq_ovl opt; opt.strategy = cl->ovl_strategy; opt.priority2 = cl->priority2+1; opt.penalty = (cl->penalty*1000)/HZ; RTA_PUT(skb, TCA_CBQ_OVL_STRATEGY, sizeof(opt), &opt); return skb->len; rtattr_failure: skb_trim(skb, b - skb->data); return -1; }
1,457
1
void block_job_yield(BlockJob *job) { assert(job->busy); /* Check cancellation *before* setting busy = false, too! */ if (block_job_is_cancelled(job)) { return; } job->busy = false; if (!block_job_should_pause(job)) { qemu_coroutine_yield(); } job->busy = true; block_job_pause_point(job); }
void block_job_yield(BlockJob *job) { assert(job->busy); if (block_job_is_cancelled(job)) { return; } job->busy = false; if (!block_job_should_pause(job)) { qemu_coroutine_yield(); } job->busy = true; block_job_pause_point(job); }
1,458
0
inline typename V::SetType FBUnserializer<V>::unserializeSet(size_t depth) { p_ += CODE_SIZE; // the set size is written so we can reserve it in the set // in future. Skip past it for now. unserializeInt64(); typename V::SetType ret = V::createSet(); size_t code = nextCode(); while (code != FB_SERIALIZE_STOP) { V::setAppend(ret, unserializeThing(depth + 1)); code = nextCode(); } p_ += CODE_SIZE; return ret; }
inline typename V::SetType FBUnserializer<V>::unserializeSet(size_t depth) { p_ += CODE_SIZE; unserializeInt64(); typename V::SetType ret = V::createSet(); size_t code = nextCode(); while (code != FB_SERIALIZE_STOP) { V::setAppend(ret, unserializeThing(depth + 1)); code = nextCode(); } p_ += CODE_SIZE; return ret; }
1,460
1
static int rsvp_dump(struct tcf_proto *tp, unsigned long fh, struct sk_buff *skb, struct tcmsg *t) { struct rsvp_filter *f = (struct rsvp_filter*)fh; struct rsvp_session *s; unsigned char *b = skb->tail; struct rtattr *rta; struct tc_rsvp_pinfo pinfo; if (f == NULL) return skb->len; s = f->sess; t->tcm_handle = f->handle; rta = (struct rtattr*)b; RTA_PUT(skb, TCA_OPTIONS, 0, NULL); RTA_PUT(skb, TCA_RSVP_DST, sizeof(s->dst), &s->dst); pinfo.dpi = s->dpi; pinfo.spi = f->spi; pinfo.protocol = s->protocol; pinfo.tunnelid = s->tunnelid; pinfo.tunnelhdr = f->tunnelhdr; RTA_PUT(skb, TCA_RSVP_PINFO, sizeof(pinfo), &pinfo); if (f->res.classid) RTA_PUT(skb, TCA_RSVP_CLASSID, 4, &f->res.classid); if (((f->handle>>8)&0xFF) != 16) RTA_PUT(skb, TCA_RSVP_SRC, sizeof(f->src), f->src); if (tcf_exts_dump(skb, &f->exts, &rsvp_ext_map) < 0) goto rtattr_failure; rta->rta_len = skb->tail - b; if (tcf_exts_dump_stats(skb, &f->exts, &rsvp_ext_map) < 0) goto rtattr_failure; return skb->len; rtattr_failure: skb_trim(skb, b - skb->data); return -1; }
static int rsvp_dump(struct tcf_proto *tp, unsigned long fh, struct sk_buff *skb, struct tcmsg *t) { struct rsvp_filter *f = (struct rsvp_filter*)fh; struct rsvp_session *s; unsigned char *b = skb->tail; struct rtattr *rta; struct tc_rsvp_pinfo pinfo; if (f == NULL) return skb->len; s = f->sess; t->tcm_handle = f->handle; rta = (struct rtattr*)b; RTA_PUT(skb, TCA_OPTIONS, 0, NULL); RTA_PUT(skb, TCA_RSVP_DST, sizeof(s->dst), &s->dst); pinfo.dpi = s->dpi; pinfo.spi = f->spi; pinfo.protocol = s->protocol; pinfo.tunnelid = s->tunnelid; pinfo.tunnelhdr = f->tunnelhdr; RTA_PUT(skb, TCA_RSVP_PINFO, sizeof(pinfo), &pinfo); if (f->res.classid) RTA_PUT(skb, TCA_RSVP_CLASSID, 4, &f->res.classid); if (((f->handle>>8)&0xFF) != 16) RTA_PUT(skb, TCA_RSVP_SRC, sizeof(f->src), f->src); if (tcf_exts_dump(skb, &f->exts, &rsvp_ext_map) < 0) goto rtattr_failure; rta->rta_len = skb->tail - b; if (tcf_exts_dump_stats(skb, &f->exts, &rsvp_ext_map) < 0) goto rtattr_failure; return skb->len; rtattr_failure: skb_trim(skb, b - skb->data); return -1; }
1,461
1
static int udp_close(URLContext *h) { UDPContext *s = h->priv_data; if (s->is_multicast && (h->flags & AVIO_FLAG_READ)) udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr,(struct sockaddr *)&s->local_addr_storage); closesocket(s->udp_fd); #if HAVE_PTHREAD_CANCEL if (s->thread_started) { int ret; pthread_cancel(s->circular_buffer_thread); ret = pthread_join(s->circular_buffer_thread, NULL); if (ret != 0) av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", strerror(ret)); pthread_mutex_destroy(&s->mutex); pthread_cond_destroy(&s->cond); } #endif av_fifo_freep(&s->fifo); return 0; }
static int udp_close(URLContext *h) { UDPContext *s = h->priv_data; if (s->is_multicast && (h->flags & AVIO_FLAG_READ)) udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr,(struct sockaddr *)&s->local_addr_storage); closesocket(s->udp_fd); #if HAVE_PTHREAD_CANCEL if (s->thread_started) { int ret; pthread_cancel(s->circular_buffer_thread); ret = pthread_join(s->circular_buffer_thread, NULL); if (ret != 0) av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", strerror(ret)); pthread_mutex_destroy(&s->mutex); pthread_cond_destroy(&s->cond); } #endif av_fifo_freep(&s->fifo); return 0; }
1,462
0
int rose_parse_facilities(unsigned char *p, struct rose_facilities_struct *facilities) { int facilities_len, len; facilities_len = *p++; if (facilities_len == 0) return 0; while (facilities_len > 0) { if (*p == 0x00) { facilities_len--; p++; switch (*p) { case FAC_NATIONAL: /* National */ len = rose_parse_national(p + 1, facilities, facilities_len - 1); if (len < 0) return 0; facilities_len -= len + 1; p += len + 1; break; case FAC_CCITT: /* CCITT */ len = rose_parse_ccitt(p + 1, facilities, facilities_len - 1); if (len < 0) return 0; facilities_len -= len + 1; p += len + 1; break; default: printk(KERN_DEBUG "ROSE: rose_parse_facilities - unknown facilities family %02X\n", *p); facilities_len--; p++; break; } } else break; /* Error in facilities format */ } return 1; }
int rose_parse_facilities(unsigned char *p, struct rose_facilities_struct *facilities) { int facilities_len, len; facilities_len = *p++; if (facilities_len == 0) return 0; while (facilities_len > 0) { if (*p == 0x00) { facilities_len--; p++; switch (*p) { case FAC_NATIONAL: len = rose_parse_national(p + 1, facilities, facilities_len - 1); if (len < 0) return 0; facilities_len -= len + 1; p += len + 1; break; case FAC_CCITT: len = rose_parse_ccitt(p + 1, facilities, facilities_len - 1); if (len < 0) return 0; facilities_len -= len + 1; p += len + 1; break; default: printk(KERN_DEBUG "ROSE: rose_parse_facilities - unknown facilities family %02X\n", *p); facilities_len--; p++; break; } } else break; } return 1; }
1,463
0
static inline int pfkey_sockaddr_len ( sa_family_t family ) { switch ( family ) { case AF_INET : return sizeof ( struct sockaddr_in ) ; # if IS_ENABLED ( CONFIG_IPV6 ) case AF_INET6 : return sizeof ( struct sockaddr_in6 ) ; # endif } return 0 ; }
static inline int pfkey_sockaddr_len ( sa_family_t family ) { switch ( family ) { case AF_INET : return sizeof ( struct sockaddr_in ) ; # if IS_ENABLED ( CONFIG_IPV6 ) case AF_INET6 : return sizeof ( struct sockaddr_in6 ) ; # endif } return 0 ; }
1,464
0
int qemuMonitorJSONGetMemoryStats ( qemuMonitorPtr mon , virDomainMemoryStatPtr stats , unsigned int nr_stats ) { int ret ; int got = 0 ; virJSONValuePtr cmd = qemuMonitorJSONMakeCommand ( "query-balloon" , NULL ) ; virJSONValuePtr reply = NULL ; if ( ! cmd ) return - 1 ; ret = qemuMonitorJSONCommand ( mon , cmd , & reply ) ; if ( ret == 0 ) { if ( qemuMonitorJSONHasError ( reply , "DeviceNotActive" ) || qemuMonitorJSONHasError ( reply , "KVMMissingCap" ) ) goto cleanup ; ret = qemuMonitorJSONCheckError ( cmd , reply ) ; if ( ret == 0 ) { virJSONValuePtr data ; unsigned long long mem ; if ( ! ( data = virJSONValueObjectGet ( reply , "return" ) ) ) { qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "info balloon reply was missing return data" ) ) ; ret = - 1 ; goto cleanup ; } if ( virJSONValueObjectHasKey ( data , "actual" ) && ( got < nr_stats ) ) { if ( virJSONValueObjectGetNumberUlong ( data , "actual" , & mem ) < 0 ) { qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "info balloon reply was missing balloon actual" ) ) ; ret = - 1 ; goto cleanup ; } stats [ got ] . tag = VIR_DOMAIN_MEMORY_STAT_ACTUAL_BALLOON ; stats [ got ] . val = ( mem / 1024 ) ; got ++ ; } if ( virJSONValueObjectHasKey ( data , "mem_swapped_in" ) && ( got < nr_stats ) ) { if ( virJSONValueObjectGetNumberUlong ( data , "mem_swapped_in" , & mem ) < 0 ) { qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "info balloon reply was missing balloon mem_swapped_in" ) ) ; ret = - 1 ; goto cleanup ; } stats [ got ] . tag = VIR_DOMAIN_MEMORY_STAT_SWAP_IN ; stats [ got ] . val = ( mem / 1024 ) ; got ++ ; } if ( virJSONValueObjectHasKey ( data , "mem_swapped_out" ) && ( got < nr_stats ) ) { if ( virJSONValueObjectGetNumberUlong ( data , "mem_swapped_out" , & mem ) < 0 ) { qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "info balloon reply was missing balloon mem_swapped_out" ) ) ; ret = - 1 ; goto cleanup ; } stats [ got ] . tag = VIR_DOMAIN_MEMORY_STAT_SWAP_OUT ; stats [ got ] . val = ( mem / 1024 ) ; got ++ ; } if ( virJSONValueObjectHasKey ( data , "major_page_faults" ) && ( got < nr_stats ) ) { if ( virJSONValueObjectGetNumberUlong ( data , "major_page_faults" , & mem ) < 0 ) { qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "info balloon reply was missing balloon major_page_faults" ) ) ; ret = - 1 ; goto cleanup ; } stats [ got ] . tag = VIR_DOMAIN_MEMORY_STAT_MAJOR_FAULT ; stats [ got ] . val = mem ; got ++ ; } if ( virJSONValueObjectHasKey ( data , "minor_page_faults" ) && ( got < nr_stats ) ) { if ( virJSONValueObjectGetNumberUlong ( data , "minor_page_faults" , & mem ) < 0 ) { qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "info balloon reply was missing balloon minor_page_faults" ) ) ; ret = - 1 ; goto cleanup ; } stats [ got ] . tag = VIR_DOMAIN_MEMORY_STAT_MINOR_FAULT ; stats [ got ] . val = mem ; got ++ ; } if ( virJSONValueObjectHasKey ( data , "free_mem" ) && ( got < nr_stats ) ) { if ( virJSONValueObjectGetNumberUlong ( data , "free_mem" , & mem ) < 0 ) { qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "info balloon reply was missing balloon free_mem" ) ) ; ret = - 1 ; goto cleanup ; } stats [ got ] . tag = VIR_DOMAIN_MEMORY_STAT_UNUSED ; stats [ got ] . val = ( mem / 1024 ) ; got ++ ; } if ( virJSONValueObjectHasKey ( data , "total_mem" ) && ( got < nr_stats ) ) { if ( virJSONValueObjectGetNumberUlong ( data , "total_mem" , & mem ) < 0 ) { qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "info balloon reply was missing balloon total_mem" ) ) ; ret = - 1 ; goto cleanup ; } stats [ got ] . tag = VIR_DOMAIN_MEMORY_STAT_AVAILABLE ; stats [ got ] . val = ( mem / 1024 ) ; got ++ ; } } } if ( got > 0 ) ret = got ; cleanup : virJSONValueFree ( cmd ) ; virJSONValueFree ( reply ) ; return ret ; }
int qemuMonitorJSONGetMemoryStats ( qemuMonitorPtr mon , virDomainMemoryStatPtr stats , unsigned int nr_stats ) { int ret ; int got = 0 ; virJSONValuePtr cmd = qemuMonitorJSONMakeCommand ( "query-balloon" , NULL ) ; virJSONValuePtr reply = NULL ; if ( ! cmd ) return - 1 ; ret = qemuMonitorJSONCommand ( mon , cmd , & reply ) ; if ( ret == 0 ) { if ( qemuMonitorJSONHasError ( reply , "DeviceNotActive" ) || qemuMonitorJSONHasError ( reply , "KVMMissingCap" ) ) goto cleanup ; ret = qemuMonitorJSONCheckError ( cmd , reply ) ; if ( ret == 0 ) { virJSONValuePtr data ; unsigned long long mem ; if ( ! ( data = virJSONValueObjectGet ( reply , "return" ) ) ) { qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "info balloon reply was missing return data" ) ) ; ret = - 1 ; goto cleanup ; } if ( virJSONValueObjectHasKey ( data , "actual" ) && ( got < nr_stats ) ) { if ( virJSONValueObjectGetNumberUlong ( data , "actual" , & mem ) < 0 ) { qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "info balloon reply was missing balloon actual" ) ) ; ret = - 1 ; goto cleanup ; } stats [ got ] . tag = VIR_DOMAIN_MEMORY_STAT_ACTUAL_BALLOON ; stats [ got ] . val = ( mem / 1024 ) ; got ++ ; } if ( virJSONValueObjectHasKey ( data , "mem_swapped_in" ) && ( got < nr_stats ) ) { if ( virJSONValueObjectGetNumberUlong ( data , "mem_swapped_in" , & mem ) < 0 ) { qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "info balloon reply was missing balloon mem_swapped_in" ) ) ; ret = - 1 ; goto cleanup ; } stats [ got ] . tag = VIR_DOMAIN_MEMORY_STAT_SWAP_IN ; stats [ got ] . val = ( mem / 1024 ) ; got ++ ; } if ( virJSONValueObjectHasKey ( data , "mem_swapped_out" ) && ( got < nr_stats ) ) { if ( virJSONValueObjectGetNumberUlong ( data , "mem_swapped_out" , & mem ) < 0 ) { qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "info balloon reply was missing balloon mem_swapped_out" ) ) ; ret = - 1 ; goto cleanup ; } stats [ got ] . tag = VIR_DOMAIN_MEMORY_STAT_SWAP_OUT ; stats [ got ] . val = ( mem / 1024 ) ; got ++ ; } if ( virJSONValueObjectHasKey ( data , "major_page_faults" ) && ( got < nr_stats ) ) { if ( virJSONValueObjectGetNumberUlong ( data , "major_page_faults" , & mem ) < 0 ) { qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "info balloon reply was missing balloon major_page_faults" ) ) ; ret = - 1 ; goto cleanup ; } stats [ got ] . tag = VIR_DOMAIN_MEMORY_STAT_MAJOR_FAULT ; stats [ got ] . val = mem ; got ++ ; } if ( virJSONValueObjectHasKey ( data , "minor_page_faults" ) && ( got < nr_stats ) ) { if ( virJSONValueObjectGetNumberUlong ( data , "minor_page_faults" , & mem ) < 0 ) { qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "info balloon reply was missing balloon minor_page_faults" ) ) ; ret = - 1 ; goto cleanup ; } stats [ got ] . tag = VIR_DOMAIN_MEMORY_STAT_MINOR_FAULT ; stats [ got ] . val = mem ; got ++ ; } if ( virJSONValueObjectHasKey ( data , "free_mem" ) && ( got < nr_stats ) ) { if ( virJSONValueObjectGetNumberUlong ( data , "free_mem" , & mem ) < 0 ) { qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "info balloon reply was missing balloon free_mem" ) ) ; ret = - 1 ; goto cleanup ; } stats [ got ] . tag = VIR_DOMAIN_MEMORY_STAT_UNUSED ; stats [ got ] . val = ( mem / 1024 ) ; got ++ ; } if ( virJSONValueObjectHasKey ( data , "total_mem" ) && ( got < nr_stats ) ) { if ( virJSONValueObjectGetNumberUlong ( data , "total_mem" , & mem ) < 0 ) { qemuReportError ( VIR_ERR_INTERNAL_ERROR , "%s" , _ ( "info balloon reply was missing balloon total_mem" ) ) ; ret = - 1 ; goto cleanup ; } stats [ got ] . tag = VIR_DOMAIN_MEMORY_STAT_AVAILABLE ; stats [ got ] . val = ( mem / 1024 ) ; got ++ ; } } } if ( got > 0 ) ret = got ; cleanup : virJSONValueFree ( cmd ) ; virJSONValueFree ( reply ) ; return ret ; }
1,465
1
static int rose_parse_national(unsigned char *p, struct rose_facilities_struct *facilities, int len) { unsigned char *pt; unsigned char l, lg, n = 0; int fac_national_digis_received = 0; do { switch (*p & 0xC0) { case 0x00: p += 2; n += 2; len -= 2; break; case 0x40: if (*p == FAC_NATIONAL_RAND) facilities->rand = ((p[1] << 8) & 0xFF00) + ((p[2] << 0) & 0x00FF); p += 3; n += 3; len -= 3; break; case 0x80: p += 4; n += 4; len -= 4; break; case 0xC0: l = p[1]; if (*p == FAC_NATIONAL_DEST_DIGI) { if (!fac_national_digis_received) { memcpy(&facilities->source_digis[0], p + 2, AX25_ADDR_LEN); facilities->source_ndigis = 1; } } else if (*p == FAC_NATIONAL_SRC_DIGI) { if (!fac_national_digis_received) { memcpy(&facilities->dest_digis[0], p + 2, AX25_ADDR_LEN); facilities->dest_ndigis = 1; } } else if (*p == FAC_NATIONAL_FAIL_CALL) { memcpy(&facilities->fail_call, p + 2, AX25_ADDR_LEN); } else if (*p == FAC_NATIONAL_FAIL_ADD) { memcpy(&facilities->fail_addr, p + 3, ROSE_ADDR_LEN); } else if (*p == FAC_NATIONAL_DIGIS) { fac_national_digis_received = 1; facilities->source_ndigis = 0; facilities->dest_ndigis = 0; for (pt = p + 2, lg = 0 ; lg < l ; pt += AX25_ADDR_LEN, lg += AX25_ADDR_LEN) { if (pt[6] & AX25_HBIT) memcpy(&facilities->dest_digis[facilities->dest_ndigis++], pt, AX25_ADDR_LEN); else memcpy(&facilities->source_digis[facilities->source_ndigis++], pt, AX25_ADDR_LEN); } } p += l + 2; n += l + 2; len -= l + 2; break; } } while (*p != 0x00 && len > 0); return n; }
static int rose_parse_national(unsigned char *p, struct rose_facilities_struct *facilities, int len) { unsigned char *pt; unsigned char l, lg, n = 0; int fac_national_digis_received = 0; do { switch (*p & 0xC0) { case 0x00: p += 2; n += 2; len -= 2; break; case 0x40: if (*p == FAC_NATIONAL_RAND) facilities->rand = ((p[1] << 8) & 0xFF00) + ((p[2] << 0) & 0x00FF); p += 3; n += 3; len -= 3; break; case 0x80: p += 4; n += 4; len -= 4; break; case 0xC0: l = p[1]; if (*p == FAC_NATIONAL_DEST_DIGI) { if (!fac_national_digis_received) { memcpy(&facilities->source_digis[0], p + 2, AX25_ADDR_LEN); facilities->source_ndigis = 1; } } else if (*p == FAC_NATIONAL_SRC_DIGI) { if (!fac_national_digis_received) { memcpy(&facilities->dest_digis[0], p + 2, AX25_ADDR_LEN); facilities->dest_ndigis = 1; } } else if (*p == FAC_NATIONAL_FAIL_CALL) { memcpy(&facilities->fail_call, p + 2, AX25_ADDR_LEN); } else if (*p == FAC_NATIONAL_FAIL_ADD) { memcpy(&facilities->fail_addr, p + 3, ROSE_ADDR_LEN); } else if (*p == FAC_NATIONAL_DIGIS) { fac_national_digis_received = 1; facilities->source_ndigis = 0; facilities->dest_ndigis = 0; for (pt = p + 2, lg = 0 ; lg < l ; pt += AX25_ADDR_LEN, lg += AX25_ADDR_LEN) { if (pt[6] & AX25_HBIT) memcpy(&facilities->dest_digis[facilities->dest_ndigis++], pt, AX25_ADDR_LEN); else memcpy(&facilities->source_digis[facilities->source_ndigis++], pt, AX25_ADDR_LEN); } } p += l + 2; n += l + 2; len -= l + 2; break; } } while (*p != 0x00 && len > 0); return n; }
1,466
1
static int inet6_fill_prefix(struct sk_buff *skb, struct inet6_dev *idev, struct prefix_info *pinfo, u32 pid, u32 seq, int event, unsigned int flags) { struct prefixmsg *pmsg; struct nlmsghdr *nlh; unsigned char *b = skb->tail; struct prefix_cacheinfo ci; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*pmsg), flags); pmsg = NLMSG_DATA(nlh); pmsg->prefix_family = AF_INET6; pmsg->prefix_ifindex = idev->dev->ifindex; pmsg->prefix_len = pinfo->prefix_len; pmsg->prefix_type = pinfo->type; pmsg->prefix_flags = 0; if (pinfo->onlink) pmsg->prefix_flags |= IF_PREFIX_ONLINK; if (pinfo->autoconf) pmsg->prefix_flags |= IF_PREFIX_AUTOCONF; RTA_PUT(skb, PREFIX_ADDRESS, sizeof(pinfo->prefix), &pinfo->prefix); ci.preferred_time = ntohl(pinfo->prefered); ci.valid_time = ntohl(pinfo->valid); RTA_PUT(skb, PREFIX_CACHEINFO, sizeof(ci), &ci); nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: rtattr_failure: skb_trim(skb, b - skb->data); return -1; }
static int inet6_fill_prefix(struct sk_buff *skb, struct inet6_dev *idev, struct prefix_info *pinfo, u32 pid, u32 seq, int event, unsigned int flags) { struct prefixmsg *pmsg; struct nlmsghdr *nlh; unsigned char *b = skb->tail; struct prefix_cacheinfo ci; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*pmsg), flags); pmsg = NLMSG_DATA(nlh); pmsg->prefix_family = AF_INET6; pmsg->prefix_ifindex = idev->dev->ifindex; pmsg->prefix_len = pinfo->prefix_len; pmsg->prefix_type = pinfo->type; pmsg->prefix_flags = 0; if (pinfo->onlink) pmsg->prefix_flags |= IF_PREFIX_ONLINK; if (pinfo->autoconf) pmsg->prefix_flags |= IF_PREFIX_AUTOCONF; RTA_PUT(skb, PREFIX_ADDRESS, sizeof(pinfo->prefix), &pinfo->prefix); ci.preferred_time = ntohl(pinfo->prefered); ci.valid_time = ntohl(pinfo->valid); RTA_PUT(skb, PREFIX_CACHEINFO, sizeof(ci), &ci); nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: rtattr_failure: skb_trim(skb, b - skb->data); return -1; }
1,467
1
static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac, uint8_t (*layout_map)[3], GetBitContext *gb, int byte_align_ref) { int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc; int sampling_index; int comment_len; int tags; skip_bits(gb, 2); // object_type sampling_index = get_bits(gb, 4); if (m4ac->sampling_index != sampling_index) av_log(avctx, AV_LOG_WARNING, "Sample rate index in program config element does not " "match the sample rate index configured by the container.\n"); num_front = get_bits(gb, 4); num_side = get_bits(gb, 4); num_back = get_bits(gb, 4); num_lfe = get_bits(gb, 2); num_assoc_data = get_bits(gb, 3); num_cc = get_bits(gb, 4); if (get_bits1(gb)) skip_bits(gb, 4); // mono_mixdown_tag if (get_bits1(gb)) skip_bits(gb, 4); // stereo_mixdown_tag if (get_bits1(gb)) skip_bits(gb, 3); // mixdown_coeff_index and pseudo_surround if (get_bits_left(gb) < 4 * (num_front + num_side + num_back + num_lfe + num_assoc_data + num_cc)) { av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err); return -1; } decode_channel_map(layout_map , AAC_CHANNEL_FRONT, gb, num_front); tags = num_front; decode_channel_map(layout_map + tags, AAC_CHANNEL_SIDE, gb, num_side); tags += num_side; decode_channel_map(layout_map + tags, AAC_CHANNEL_BACK, gb, num_back); tags += num_back; decode_channel_map(layout_map + tags, AAC_CHANNEL_LFE, gb, num_lfe); tags += num_lfe; skip_bits_long(gb, 4 * num_assoc_data); decode_channel_map(layout_map + tags, AAC_CHANNEL_CC, gb, num_cc); tags += num_cc; relative_align_get_bits(gb, byte_align_ref); /* comment field, first byte is length */ comment_len = get_bits(gb, 8) * 8; if (get_bits_left(gb) < comment_len) { av_log(avctx, AV_LOG_ERROR, "decode_pce: " overread_err); return AVERROR_INVALIDDATA; } skip_bits_long(gb, comment_len); return tags; }
static int decode_pce(AVCodecContext *avctx, MPEG4AudioConfig *m4ac, uint8_t (*layout_map)[3], GetBitContext *gb, int byte_align_ref) { int num_front, num_side, num_back, num_lfe, num_assoc_data, num_cc; int sampling_index; int comment_len; int tags; skip_bits(gb, 2);
1,468
0
static void DecoderProcessSpu ( decoder_t * p_dec , block_t * p_block , bool b_flush ) { decoder_owner_sys_t * p_owner = p_dec -> p_owner ; input_thread_t * p_input = p_owner -> p_input ; vout_thread_t * p_vout ; subpicture_t * p_spu ; while ( ( p_spu = p_dec -> pf_decode_sub ( p_dec , p_block ? & p_block : NULL ) ) ) { if ( p_input != NULL ) { vlc_mutex_lock ( & p_input -> p -> counters . counters_lock ) ; stats_Update ( p_input -> p -> counters . p_decoded_sub , 1 , NULL ) ; vlc_mutex_unlock ( & p_input -> p -> counters . counters_lock ) ; } p_vout = input_resource_HoldVout ( p_owner -> p_resource ) ; if ( p_vout && p_owner -> p_spu_vout == p_vout ) { if ( p_spu -> i_start > VLC_TS_INVALID && p_spu -> i_start < p_owner -> i_preroll_end && ( p_spu -> i_stop <= VLC_TS_INVALID || p_spu -> i_stop < p_owner -> i_preroll_end ) ) { subpicture_Delete ( p_spu ) ; } else { DecoderPlaySpu ( p_dec , p_spu ) ; } } else { subpicture_Delete ( p_spu ) ; } if ( p_vout ) vlc_object_release ( p_vout ) ; } if ( b_flush && p_owner -> p_spu_vout ) { p_vout = input_resource_HoldVout ( p_owner -> p_resource ) ; if ( p_vout && p_owner -> p_spu_vout == p_vout ) vout_FlushSubpictureChannel ( p_vout , p_owner -> i_spu_channel ) ; if ( p_vout ) vlc_object_release ( p_vout ) ; } }
static void DecoderProcessSpu ( decoder_t * p_dec , block_t * p_block , bool b_flush ) { decoder_owner_sys_t * p_owner = p_dec -> p_owner ; input_thread_t * p_input = p_owner -> p_input ; vout_thread_t * p_vout ; subpicture_t * p_spu ; while ( ( p_spu = p_dec -> pf_decode_sub ( p_dec , p_block ? & p_block : NULL ) ) ) { if ( p_input != NULL ) { vlc_mutex_lock ( & p_input -> p -> counters . counters_lock ) ; stats_Update ( p_input -> p -> counters . p_decoded_sub , 1 , NULL ) ; vlc_mutex_unlock ( & p_input -> p -> counters . counters_lock ) ; } p_vout = input_resource_HoldVout ( p_owner -> p_resource ) ; if ( p_vout && p_owner -> p_spu_vout == p_vout ) { if ( p_spu -> i_start > VLC_TS_INVALID && p_spu -> i_start < p_owner -> i_preroll_end && ( p_spu -> i_stop <= VLC_TS_INVALID || p_spu -> i_stop < p_owner -> i_preroll_end ) ) { subpicture_Delete ( p_spu ) ; } else { DecoderPlaySpu ( p_dec , p_spu ) ; } } else { subpicture_Delete ( p_spu ) ; } if ( p_vout ) vlc_object_release ( p_vout ) ; } if ( b_flush && p_owner -> p_spu_vout ) { p_vout = input_resource_HoldVout ( p_owner -> p_resource ) ; if ( p_vout && p_owner -> p_spu_vout == p_vout ) vout_FlushSubpictureChannel ( p_vout , p_owner -> i_spu_channel ) ; if ( p_vout ) vlc_object_release ( p_vout ) ; } }
1,471
0
FBUnserializer<V>::unserializeThing(size_t depth) { if (UNLIKELY(depth > 1024)) { throw UnserializeError("depth > 1024"); } size_t code = nextCode(); switch (code) { case FB_SERIALIZE_BYTE: case FB_SERIALIZE_I16: case FB_SERIALIZE_I32: case FB_SERIALIZE_I64: return V::fromInt64(unserializeInt64()); case FB_SERIALIZE_VARCHAR: case FB_SERIALIZE_STRING: return V::fromString(unserializeString()); case FB_SERIALIZE_STRUCT: return V::fromMap(unserializeMap(depth)); case FB_SERIALIZE_NULL: ++p_; return V::createNull(); case FB_SERIALIZE_DOUBLE: return V::fromDouble(unserializeDouble()); case FB_SERIALIZE_BOOLEAN: return V::fromBool(unserializeBoolean()); case FB_SERIALIZE_VECTOR: return V::fromVector(unserializeVector(depth)); case FB_SERIALIZE_LIST: return V::fromVector(unserializeList(depth)); case FB_SERIALIZE_SET: return V::fromSet(unserializeSet(depth)); default: throw UnserializeError("Invalid code: " + folly::to<std::string>(code) + " at location " + folly::to<std::string>(p_)); } }
FBUnserializer<V>::unserializeThing(size_t depth) { if (UNLIKELY(depth > 1024)) { throw UnserializeError("depth > 1024"); } size_t code = nextCode(); switch (code) { case FB_SERIALIZE_BYTE: case FB_SERIALIZE_I16: case FB_SERIALIZE_I32: case FB_SERIALIZE_I64: return V::fromInt64(unserializeInt64()); case FB_SERIALIZE_VARCHAR: case FB_SERIALIZE_STRING: return V::fromString(unserializeString()); case FB_SERIALIZE_STRUCT: return V::fromMap(unserializeMap(depth)); case FB_SERIALIZE_NULL: ++p_; return V::createNull(); case FB_SERIALIZE_DOUBLE: return V::fromDouble(unserializeDouble()); case FB_SERIALIZE_BOOLEAN: return V::fromBool(unserializeBoolean()); case FB_SERIALIZE_VECTOR: return V::fromVector(unserializeVector(depth)); case FB_SERIALIZE_LIST: return V::fromVector(unserializeList(depth)); case FB_SERIALIZE_SET: return V::fromSet(unserializeSet(depth)); default: throw UnserializeError("Invalid code: " + folly::to<std::string>(code) + " at location " + folly::to<std::string>(p_)); } }
1,472
1
static int neightbl_fill_info(struct neigh_table *tbl, struct sk_buff *skb, struct netlink_callback *cb) { struct nlmsghdr *nlh; struct ndtmsg *ndtmsg; nlh = NLMSG_NEW_ANSWER(skb, cb, RTM_NEWNEIGHTBL, sizeof(struct ndtmsg), NLM_F_MULTI); ndtmsg = NLMSG_DATA(nlh); read_lock_bh(&tbl->lock); ndtmsg->ndtm_family = tbl->family; RTA_PUT_STRING(skb, NDTA_NAME, tbl->id); RTA_PUT_MSECS(skb, NDTA_GC_INTERVAL, tbl->gc_interval); RTA_PUT_U32(skb, NDTA_THRESH1, tbl->gc_thresh1); RTA_PUT_U32(skb, NDTA_THRESH2, tbl->gc_thresh2); RTA_PUT_U32(skb, NDTA_THRESH3, tbl->gc_thresh3); { unsigned long now = jiffies; unsigned int flush_delta = now - tbl->last_flush; unsigned int rand_delta = now - tbl->last_rand; struct ndt_config ndc = { .ndtc_key_len = tbl->key_len, .ndtc_entry_size = tbl->entry_size, .ndtc_entries = atomic_read(&tbl->entries), .ndtc_last_flush = jiffies_to_msecs(flush_delta), .ndtc_last_rand = jiffies_to_msecs(rand_delta), .ndtc_hash_rnd = tbl->hash_rnd, .ndtc_hash_mask = tbl->hash_mask, .ndtc_hash_chain_gc = tbl->hash_chain_gc, .ndtc_proxy_qlen = tbl->proxy_queue.qlen, }; RTA_PUT(skb, NDTA_CONFIG, sizeof(ndc), &ndc); } { int cpu; struct ndt_stats ndst; memset(&ndst, 0, sizeof(ndst)); for (cpu = 0; cpu < NR_CPUS; cpu++) { struct neigh_statistics *st; if (!cpu_possible(cpu)) continue; st = per_cpu_ptr(tbl->stats, cpu); ndst.ndts_allocs += st->allocs; ndst.ndts_destroys += st->destroys; ndst.ndts_hash_grows += st->hash_grows; ndst.ndts_res_failed += st->res_failed; ndst.ndts_lookups += st->lookups; ndst.ndts_hits += st->hits; ndst.ndts_rcv_probes_mcast += st->rcv_probes_mcast; ndst.ndts_rcv_probes_ucast += st->rcv_probes_ucast; ndst.ndts_periodic_gc_runs += st->periodic_gc_runs; ndst.ndts_forced_gc_runs += st->forced_gc_runs; } RTA_PUT(skb, NDTA_STATS, sizeof(ndst), &ndst); } BUG_ON(tbl->parms.dev); if (neightbl_fill_parms(skb, &tbl->parms) < 0) goto rtattr_failure; read_unlock_bh(&tbl->lock); return NLMSG_END(skb, nlh); rtattr_failure: read_unlock_bh(&tbl->lock); return NLMSG_CANCEL(skb, nlh); nlmsg_failure: return -1; }
static int neightbl_fill_info(struct neigh_table *tbl, struct sk_buff *skb, struct netlink_callback *cb) { struct nlmsghdr *nlh; struct ndtmsg *ndtmsg; nlh = NLMSG_NEW_ANSWER(skb, cb, RTM_NEWNEIGHTBL, sizeof(struct ndtmsg), NLM_F_MULTI); ndtmsg = NLMSG_DATA(nlh); read_lock_bh(&tbl->lock); ndtmsg->ndtm_family = tbl->family; RTA_PUT_STRING(skb, NDTA_NAME, tbl->id); RTA_PUT_MSECS(skb, NDTA_GC_INTERVAL, tbl->gc_interval); RTA_PUT_U32(skb, NDTA_THRESH1, tbl->gc_thresh1); RTA_PUT_U32(skb, NDTA_THRESH2, tbl->gc_thresh2); RTA_PUT_U32(skb, NDTA_THRESH3, tbl->gc_thresh3); { unsigned long now = jiffies; unsigned int flush_delta = now - tbl->last_flush; unsigned int rand_delta = now - tbl->last_rand; struct ndt_config ndc = { .ndtc_key_len = tbl->key_len, .ndtc_entry_size = tbl->entry_size, .ndtc_entries = atomic_read(&tbl->entries), .ndtc_last_flush = jiffies_to_msecs(flush_delta), .ndtc_last_rand = jiffies_to_msecs(rand_delta), .ndtc_hash_rnd = tbl->hash_rnd, .ndtc_hash_mask = tbl->hash_mask, .ndtc_hash_chain_gc = tbl->hash_chain_gc, .ndtc_proxy_qlen = tbl->proxy_queue.qlen, }; RTA_PUT(skb, NDTA_CONFIG, sizeof(ndc), &ndc); } { int cpu; struct ndt_stats ndst; memset(&ndst, 0, sizeof(ndst)); for (cpu = 0; cpu < NR_CPUS; cpu++) { struct neigh_statistics *st; if (!cpu_possible(cpu)) continue; st = per_cpu_ptr(tbl->stats, cpu); ndst.ndts_allocs += st->allocs; ndst.ndts_destroys += st->destroys; ndst.ndts_hash_grows += st->hash_grows; ndst.ndts_res_failed += st->res_failed; ndst.ndts_lookups += st->lookups; ndst.ndts_hits += st->hits; ndst.ndts_rcv_probes_mcast += st->rcv_probes_mcast; ndst.ndts_rcv_probes_ucast += st->rcv_probes_ucast; ndst.ndts_periodic_gc_runs += st->periodic_gc_runs; ndst.ndts_forced_gc_runs += st->forced_gc_runs; } RTA_PUT(skb, NDTA_STATS, sizeof(ndst), &ndst); } BUG_ON(tbl->parms.dev); if (neightbl_fill_parms(skb, &tbl->parms) < 0) goto rtattr_failure; read_unlock_bh(&tbl->lock); return NLMSG_END(skb, nlh); rtattr_failure: read_unlock_bh(&tbl->lock); return NLMSG_CANCEL(skb, nlh); nlmsg_failure: return -1; }
1,474
1
int rose_rx_call_request(struct sk_buff *skb, struct net_device *dev, struct rose_neigh *neigh, unsigned int lci) { struct sock *sk; struct sock *make; struct rose_sock *make_rose; struct rose_facilities_struct facilities; int n, len; skb->sk = NULL; /* Initially we don't know who it's for */ /* * skb->data points to the rose frame start */ memset(&facilities, 0x00, sizeof(struct rose_facilities_struct)); len = (((skb->data[3] >> 4) & 0x0F) + 1) >> 1; len += (((skb->data[3] >> 0) & 0x0F) + 1) >> 1; if (!rose_parse_facilities(skb->data + len + 4, &facilities)) { rose_transmit_clear_request(neigh, lci, ROSE_INVALID_FACILITY, 76); return 0; } sk = rose_find_listener(&facilities.source_addr, &facilities.source_call); /* * We can't accept the Call Request. */ if (sk == NULL || sk_acceptq_is_full(sk) || (make = rose_make_new(sk)) == NULL) { rose_transmit_clear_request(neigh, lci, ROSE_NETWORK_CONGESTION, 120); return 0; } skb->sk = make; make->sk_state = TCP_ESTABLISHED; make_rose = rose_sk(make); make_rose->lci = lci; make_rose->dest_addr = facilities.dest_addr; make_rose->dest_call = facilities.dest_call; make_rose->dest_ndigis = facilities.dest_ndigis; for (n = 0 ; n < facilities.dest_ndigis ; n++) make_rose->dest_digis[n] = facilities.dest_digis[n]; make_rose->source_addr = facilities.source_addr; make_rose->source_call = facilities.source_call; make_rose->source_ndigis = facilities.source_ndigis; for (n = 0 ; n < facilities.source_ndigis ; n++) make_rose->source_digis[n]= facilities.source_digis[n]; make_rose->neighbour = neigh; make_rose->device = dev; make_rose->facilities = facilities; make_rose->neighbour->use++; if (rose_sk(sk)->defer) { make_rose->state = ROSE_STATE_5; } else { rose_write_internal(make, ROSE_CALL_ACCEPTED); make_rose->state = ROSE_STATE_3; rose_start_idletimer(make); } make_rose->condition = 0x00; make_rose->vs = 0; make_rose->va = 0; make_rose->vr = 0; make_rose->vl = 0; sk->sk_ack_backlog++; rose_insert_socket(make); skb_queue_head(&sk->sk_receive_queue, skb); rose_start_heartbeat(make); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb->len); return 1; }
int rose_rx_call_request(struct sk_buff *skb, struct net_device *dev, struct rose_neigh *neigh, unsigned int lci) { struct sock *sk; struct sock *make; struct rose_sock *make_rose; struct rose_facilities_struct facilities; int n, len; skb->sk = NULL; memset(&facilities, 0x00, sizeof(struct rose_facilities_struct)); len = (((skb->data[3] >> 4) & 0x0F) + 1) >> 1; len += (((skb->data[3] >> 0) & 0x0F) + 1) >> 1; if (!rose_parse_facilities(skb->data + len + 4, &facilities)) { rose_transmit_clear_request(neigh, lci, ROSE_INVALID_FACILITY, 76); return 0; } sk = rose_find_listener(&facilities.source_addr, &facilities.source_call); if (sk == NULL || sk_acceptq_is_full(sk) || (make = rose_make_new(sk)) == NULL) { rose_transmit_clear_request(neigh, lci, ROSE_NETWORK_CONGESTION, 120); return 0; } skb->sk = make; make->sk_state = TCP_ESTABLISHED; make_rose = rose_sk(make); make_rose->lci = lci; make_rose->dest_addr = facilities.dest_addr; make_rose->dest_call = facilities.dest_call; make_rose->dest_ndigis = facilities.dest_ndigis; for (n = 0 ; n < facilities.dest_ndigis ; n++) make_rose->dest_digis[n] = facilities.dest_digis[n]; make_rose->source_addr = facilities.source_addr; make_rose->source_call = facilities.source_call; make_rose->source_ndigis = facilities.source_ndigis; for (n = 0 ; n < facilities.source_ndigis ; n++) make_rose->source_digis[n]= facilities.source_digis[n]; make_rose->neighbour = neigh; make_rose->device = dev; make_rose->facilities = facilities; make_rose->neighbour->use++; if (rose_sk(sk)->defer) { make_rose->state = ROSE_STATE_5; } else { rose_write_internal(make, ROSE_CALL_ACCEPTED); make_rose->state = ROSE_STATE_3; rose_start_idletimer(make); } make_rose->condition = 0x00; make_rose->vs = 0; make_rose->va = 0; make_rose->vr = 0; make_rose->vl = 0; sk->sk_ack_backlog++; rose_insert_socket(make); skb_queue_head(&sk->sk_receive_queue, skb); rose_start_heartbeat(make); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb->len); return 1; }
1,475
0
int dissect_h245_MulticastAddress ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) { offset = dissect_per_choice ( tvb , offset , actx , tree , hf_index , ett_h245_MulticastAddress , MulticastAddress_choice , NULL ) ; return offset ; }
int dissect_h245_MulticastAddress ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) { offset = dissect_per_choice ( tvb , offset , actx , tree , hf_index , ett_h245_MulticastAddress , MulticastAddress_choice , NULL ) ; return offset ; }
1,479
0
static int evhttp_append_to_last_header ( struct evkeyvalq * headers , const char * line ) { struct evkeyval * header = TAILQ_LAST ( headers , evkeyvalq ) ; char * newval ; size_t old_len , line_len ; if ( header == NULL ) return ( - 1 ) ; old_len = strlen ( header -> value ) ; line_len = strlen ( line ) ; newval = realloc ( header -> value , old_len + line_len + 1 ) ; if ( newval == NULL ) return ( - 1 ) ; memcpy ( newval + old_len , line , line_len + 1 ) ; header -> value = newval ; return ( 0 ) ; }
static int evhttp_append_to_last_header ( struct evkeyvalq * headers , const char * line ) { struct evkeyval * header = TAILQ_LAST ( headers , evkeyvalq ) ; char * newval ; size_t old_len , line_len ; if ( header == NULL ) return ( - 1 ) ; old_len = strlen ( header -> value ) ; line_len = strlen ( line ) ; newval = realloc ( header -> value , old_len + line_len + 1 ) ; if ( newval == NULL ) return ( - 1 ) ; memcpy ( newval + old_len , line , line_len + 1 ) ; header -> value = newval ; return ( 0 ) ; }
1,480
0
FBUnserializer<V>::unserializeVector(size_t depth) { p_ += CODE_SIZE; typename V::VectorType ret = V::createVector(); size_t code = nextCode(); while (code != FB_SERIALIZE_STOP) { V::vectorAppend(ret, unserializeThing(depth + 1)); code = nextCode(); } p_ += CODE_SIZE; return ret; }
FBUnserializer<V>::unserializeVector(size_t depth) { p_ += CODE_SIZE; typename V::VectorType ret = V::createVector(); size_t code = nextCode(); while (code != FB_SERIALIZE_STOP) { V::vectorAppend(ret, unserializeThing(depth + 1)); code = nextCode(); } p_ += CODE_SIZE; return ret; }
1,481
1
static void ipmr_cache_resolve(struct mfc_cache *uc, struct mfc_cache *c) { struct sk_buff *skb; /* * Play the pending entries through our router */ while((skb=__skb_dequeue(&uc->mfc_un.unres.unresolved))) { if (skb->nh.iph->version == 0) { int err; struct nlmsghdr *nlh = (struct nlmsghdr *)skb_pull(skb, sizeof(struct iphdr)); if (ipmr_fill_mroute(skb, c, NLMSG_DATA(nlh)) > 0) { nlh->nlmsg_len = skb->tail - (u8*)nlh; } else { nlh->nlmsg_type = NLMSG_ERROR; nlh->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr)); skb_trim(skb, nlh->nlmsg_len); ((struct nlmsgerr*)NLMSG_DATA(nlh))->error = -EMSGSIZE; } err = netlink_unicast(rtnl, skb, NETLINK_CB(skb).dst_pid, MSG_DONTWAIT); } else ip_mr_forward(skb, c, 0); } }
static void ipmr_cache_resolve(struct mfc_cache *uc, struct mfc_cache *c) { struct sk_buff *skb; while((skb=__skb_dequeue(&uc->mfc_un.unres.unresolved))) { if (skb->nh.iph->version == 0) { int err; struct nlmsghdr *nlh = (struct nlmsghdr *)skb_pull(skb, sizeof(struct iphdr)); if (ipmr_fill_mroute(skb, c, NLMSG_DATA(nlh)) > 0) { nlh->nlmsg_len = skb->tail - (u8*)nlh; } else { nlh->nlmsg_type = NLMSG_ERROR; nlh->nlmsg_len = NLMSG_LENGTH(sizeof(struct nlmsgerr)); skb_trim(skb, nlh->nlmsg_len); ((struct nlmsgerr*)NLMSG_DATA(nlh))->error = -EMSGSIZE; } err = netlink_unicast(rtnl, skb, NETLINK_CB(skb).dst_pid, MSG_DONTWAIT); } else ip_mr_forward(skb, c, 0); } }
1,482
1
static void virtio_ioport_write(void *opaque, uint32_t addr, uint32_t val) { VirtIOPCIProxy *proxy = opaque; VirtIODevice *vdev = proxy->vdev; target_phys_addr_t pa; switch (addr) { case VIRTIO_PCI_GUEST_FEATURES: /* Guest does not negotiate properly? We have to assume nothing. */ if (val & (1 << VIRTIO_F_BAD_FEATURE)) { if (vdev->bad_features) val = proxy->host_features & vdev->bad_features(vdev); else val = 0; } if (vdev->set_features) vdev->set_features(vdev, val); vdev->guest_features = val; break; case VIRTIO_PCI_QUEUE_PFN: pa = (target_phys_addr_t)val << VIRTIO_PCI_QUEUE_ADDR_SHIFT; if (pa == 0) { virtio_pci_stop_ioeventfd(proxy); virtio_reset(proxy->vdev); msix_unuse_all_vectors(&proxy->pci_dev); } else virtio_queue_set_addr(vdev, vdev->queue_sel, pa); break; case VIRTIO_PCI_QUEUE_SEL: if (val < VIRTIO_PCI_QUEUE_MAX) vdev->queue_sel = val; break; case VIRTIO_PCI_QUEUE_NOTIFY: virtio_queue_notify(vdev, val); break; case VIRTIO_PCI_STATUS: if (!(val & VIRTIO_CONFIG_S_DRIVER_OK)) { virtio_pci_stop_ioeventfd(proxy); } virtio_set_status(vdev, val & 0xFF); if (val & VIRTIO_CONFIG_S_DRIVER_OK) { virtio_pci_start_ioeventfd(proxy); } if (vdev->status == 0) { virtio_reset(proxy->vdev); msix_unuse_all_vectors(&proxy->pci_dev); } /* Linux before 2.6.34 sets the device as OK without enabling the PCI device bus master bit. In this case we need to disable some safety checks. */ if ((val & VIRTIO_CONFIG_S_DRIVER_OK) && !(proxy->pci_dev.config[PCI_COMMAND] & PCI_COMMAND_MASTER)) { proxy->flags |= VIRTIO_PCI_FLAG_BUS_MASTER_BUG; } break; case VIRTIO_MSI_CONFIG_VECTOR: msix_vector_unuse(&proxy->pci_dev, vdev->config_vector); /* Make it possible for guest to discover an error took place. */ if (msix_vector_use(&proxy->pci_dev, val) < 0) val = VIRTIO_NO_VECTOR; vdev->config_vector = val; break; case VIRTIO_MSI_QUEUE_VECTOR: msix_vector_unuse(&proxy->pci_dev, virtio_queue_vector(vdev, vdev->queue_sel)); /* Make it possible for guest to discover an error took place. */ if (msix_vector_use(&proxy->pci_dev, val) < 0) val = VIRTIO_NO_VECTOR; virtio_queue_set_vector(vdev, vdev->queue_sel, val); break; default: error_report("%s: unexpected address 0x%x value 0x%x", __func__, addr, val); break; } }
static void virtio_ioport_write(void *opaque, uint32_t addr, uint32_t val) { VirtIOPCIProxy *proxy = opaque; VirtIODevice *vdev = proxy->vdev; target_phys_addr_t pa; switch (addr) { case VIRTIO_PCI_GUEST_FEATURES: if (val & (1 << VIRTIO_F_BAD_FEATURE)) { if (vdev->bad_features) val = proxy->host_features & vdev->bad_features(vdev); else val = 0; } if (vdev->set_features) vdev->set_features(vdev, val); vdev->guest_features = val; break; case VIRTIO_PCI_QUEUE_PFN: pa = (target_phys_addr_t)val << VIRTIO_PCI_QUEUE_ADDR_SHIFT; if (pa == 0) { virtio_pci_stop_ioeventfd(proxy); virtio_reset(proxy->vdev); msix_unuse_all_vectors(&proxy->pci_dev); } else virtio_queue_set_addr(vdev, vdev->queue_sel, pa); break; case VIRTIO_PCI_QUEUE_SEL: if (val < VIRTIO_PCI_QUEUE_MAX) vdev->queue_sel = val; break; case VIRTIO_PCI_QUEUE_NOTIFY: virtio_queue_notify(vdev, val); break; case VIRTIO_PCI_STATUS: if (!(val & VIRTIO_CONFIG_S_DRIVER_OK)) { virtio_pci_stop_ioeventfd(proxy); } virtio_set_status(vdev, val & 0xFF); if (val & VIRTIO_CONFIG_S_DRIVER_OK) { virtio_pci_start_ioeventfd(proxy); } if (vdev->status == 0) { virtio_reset(proxy->vdev); msix_unuse_all_vectors(&proxy->pci_dev); } if ((val & VIRTIO_CONFIG_S_DRIVER_OK) && !(proxy->pci_dev.config[PCI_COMMAND] & PCI_COMMAND_MASTER)) { proxy->flags |= VIRTIO_PCI_FLAG_BUS_MASTER_BUG; } break; case VIRTIO_MSI_CONFIG_VECTOR: msix_vector_unuse(&proxy->pci_dev, vdev->config_vector); if (msix_vector_use(&proxy->pci_dev, val) < 0) val = VIRTIO_NO_VECTOR; vdev->config_vector = val; break; case VIRTIO_MSI_QUEUE_VECTOR: msix_vector_unuse(&proxy->pci_dev, virtio_queue_vector(vdev, vdev->queue_sel)); if (msix_vector_use(&proxy->pci_dev, val) < 0) val = VIRTIO_NO_VECTOR; virtio_queue_set_vector(vdev, vdev->queue_sel, val); break; default: error_report("%s: unexpected address 0x%x value 0x%x", __func__, addr, val); break; } }
1,483
1
inline typename V::VectorType FBUnserializer<V>::unserializeVector() { p_ += CODE_SIZE; typename V::VectorType ret = V::createVector(); size_t code = nextCode(); while (code != FB_SERIALIZE_STOP) { V::vectorAppend(ret, unserializeThing()); code = nextCode(); } p_ += CODE_SIZE; return ret; }
inline typename V::VectorType FBUnserializer<V>::unserializeVector() { p_ += CODE_SIZE; typename V::VectorType ret = V::createVector(); size_t code = nextCode(); while (code != FB_SERIALIZE_STOP) { V::vectorAppend(ret, unserializeThing()); code = nextCode(); } p_ += CODE_SIZE; return ret; }
1,484
0
int ff_get_cpu_flags_x86(void) { int rval = 0; #ifdef cpuid int eax, ebx, ecx, edx; int max_std_level, max_ext_level, std_caps = 0, ext_caps = 0; int family = 0, model = 0; union { int i[3]; char c[12]; } vendor; if (!cpuid_test()) return 0; /* CPUID not supported */ cpuid(0, max_std_level, vendor.i[0], vendor.i[2], vendor.i[1]); if (max_std_level >= 1) { cpuid(1, eax, ebx, ecx, std_caps); family = ((eax >> 8) & 0xf) + ((eax >> 20) & 0xff); model = ((eax >> 4) & 0xf) + ((eax >> 12) & 0xf0); if (std_caps & (1 << 15)) rval |= AV_CPU_FLAG_CMOV; if (std_caps & (1 << 23)) rval |= AV_CPU_FLAG_MMX; if (std_caps & (1 << 25)) rval |= AV_CPU_FLAG_MMXEXT; #if HAVE_SSE if (std_caps & (1 << 25)) rval |= AV_CPU_FLAG_SSE; if (std_caps & (1 << 26)) rval |= AV_CPU_FLAG_SSE2; if (ecx & 1) rval |= AV_CPU_FLAG_SSE3; if (ecx & 0x00000200 ) rval |= AV_CPU_FLAG_SSSE3; if (ecx & 0x00080000 ) rval |= AV_CPU_FLAG_SSE4; if (ecx & 0x00100000 ) rval |= AV_CPU_FLAG_SSE42; #if HAVE_AVX /* Check OXSAVE and AVX bits */ if ((ecx & 0x18000000) == 0x18000000) { /* Check for OS support */ xgetbv(0, eax, edx); if ((eax & 0x6) == 0x6) { rval |= AV_CPU_FLAG_AVX; if (ecx & 0x00001000) rval |= AV_CPU_FLAG_FMA3; } } #endif /* HAVE_AVX */ #endif /* HAVE_SSE */ } if (max_std_level >= 7) { cpuid(7, eax, ebx, ecx, edx); #if HAVE_AVX2 if (ebx & 0x00000020) rval |= AV_CPU_FLAG_AVX2; #endif /* HAVE_AVX2 */ /* BMI1/2 don't need OS support */ if (ebx & 0x00000008) { rval |= AV_CPU_FLAG_BMI1; if (ebx & 0x00000100) rval |= AV_CPU_FLAG_BMI2; } } cpuid(0x80000000, max_ext_level, ebx, ecx, edx); if (max_ext_level >= 0x80000001) { cpuid(0x80000001, eax, ebx, ecx, ext_caps); if (ext_caps & (1U << 31)) rval |= AV_CPU_FLAG_3DNOW; if (ext_caps & (1 << 30)) rval |= AV_CPU_FLAG_3DNOWEXT; if (ext_caps & (1 << 23)) rval |= AV_CPU_FLAG_MMX; if (ext_caps & (1 << 22)) rval |= AV_CPU_FLAG_MMXEXT; /* Allow for selectively disabling SSE2 functions on AMD processors with SSE2 support but not SSE4a. This includes Athlon64, some Opteron, and some Sempron processors. MMX, SSE, or 3DNow! are faster than SSE2 often enough to utilize this special-case flag. AV_CPU_FLAG_SSE2 and AV_CPU_FLAG_SSE2SLOW are both set in this case so that SSE2 is used unless explicitly disabled by checking AV_CPU_FLAG_SSE2SLOW. */ if (!strncmp(vendor.c, "AuthenticAMD", 12) && rval & AV_CPU_FLAG_SSE2 && !(ecx & 0x00000040)) { rval |= AV_CPU_FLAG_SSE2SLOW; } /* XOP and FMA4 use the AVX instruction coding scheme, so they can't be * used unless the OS has AVX support. */ if (rval & AV_CPU_FLAG_AVX) { if (ecx & 0x00000800) rval |= AV_CPU_FLAG_XOP; if (ecx & 0x00010000) rval |= AV_CPU_FLAG_FMA4; } } if (!strncmp(vendor.c, "GenuineIntel", 12)) { if (family == 6 && (model == 9 || model == 13 || model == 14)) { /* 6/9 (pentium-m "banias"), 6/13 (pentium-m "dothan"), and * 6/14 (core1 "yonah") theoretically support sse2, but it's * usually slower than mmx, so let's just pretend they don't. * AV_CPU_FLAG_SSE2 is disabled and AV_CPU_FLAG_SSE2SLOW is * enabled so that SSE2 is not used unless explicitly enabled * by checking AV_CPU_FLAG_SSE2SLOW. The same situation * applies for AV_CPU_FLAG_SSE3 and AV_CPU_FLAG_SSE3SLOW. */ if (rval & AV_CPU_FLAG_SSE2) rval ^= AV_CPU_FLAG_SSE2SLOW | AV_CPU_FLAG_SSE2; if (rval & AV_CPU_FLAG_SSE3) rval ^= AV_CPU_FLAG_SSE3SLOW | AV_CPU_FLAG_SSE3; } /* The Atom processor has SSSE3 support, which is useful in many cases, * but sometimes the SSSE3 version is slower than the SSE2 equivalent * on the Atom, but is generally faster on other processors supporting * SSSE3. This flag allows for selectively disabling certain SSSE3 * functions on the Atom. */ if (family == 6 && model == 28) rval |= AV_CPU_FLAG_ATOM; } #endif /* cpuid */ return rval; }
int ff_get_cpu_flags_x86(void) { int rval = 0; #ifdef cpuid int eax, ebx, ecx, edx; int max_std_level, max_ext_level, std_caps = 0, ext_caps = 0; int family = 0, model = 0; union { int i[3]; char c[12]; } vendor; if (!cpuid_test()) return 0; cpuid(0, max_std_level, vendor.i[0], vendor.i[2], vendor.i[1]); if (max_std_level >= 1) { cpuid(1, eax, ebx, ecx, std_caps); family = ((eax >> 8) & 0xf) + ((eax >> 20) & 0xff); model = ((eax >> 4) & 0xf) + ((eax >> 12) & 0xf0); if (std_caps & (1 << 15)) rval |= AV_CPU_FLAG_CMOV; if (std_caps & (1 << 23)) rval |= AV_CPU_FLAG_MMX; if (std_caps & (1 << 25)) rval |= AV_CPU_FLAG_MMXEXT; #if HAVE_SSE if (std_caps & (1 << 25)) rval |= AV_CPU_FLAG_SSE; if (std_caps & (1 << 26)) rval |= AV_CPU_FLAG_SSE2; if (ecx & 1) rval |= AV_CPU_FLAG_SSE3; if (ecx & 0x00000200 ) rval |= AV_CPU_FLAG_SSSE3; if (ecx & 0x00080000 ) rval |= AV_CPU_FLAG_SSE4; if (ecx & 0x00100000 ) rval |= AV_CPU_FLAG_SSE42; #if HAVE_AVX if ((ecx & 0x18000000) == 0x18000000) { xgetbv(0, eax, edx); if ((eax & 0x6) == 0x6) { rval |= AV_CPU_FLAG_AVX; if (ecx & 0x00001000) rval |= AV_CPU_FLAG_FMA3; } } #endif #endif } if (max_std_level >= 7) { cpuid(7, eax, ebx, ecx, edx); #if HAVE_AVX2 if (ebx & 0x00000020) rval |= AV_CPU_FLAG_AVX2; #endif if (ebx & 0x00000008) { rval |= AV_CPU_FLAG_BMI1; if (ebx & 0x00000100) rval |= AV_CPU_FLAG_BMI2; } } cpuid(0x80000000, max_ext_level, ebx, ecx, edx); if (max_ext_level >= 0x80000001) { cpuid(0x80000001, eax, ebx, ecx, ext_caps); if (ext_caps & (1U << 31)) rval |= AV_CPU_FLAG_3DNOW; if (ext_caps & (1 << 30)) rval |= AV_CPU_FLAG_3DNOWEXT; if (ext_caps & (1 << 23)) rval |= AV_CPU_FLAG_MMX; if (ext_caps & (1 << 22)) rval |= AV_CPU_FLAG_MMXEXT; if (!strncmp(vendor.c, "AuthenticAMD", 12) && rval & AV_CPU_FLAG_SSE2 && !(ecx & 0x00000040)) { rval |= AV_CPU_FLAG_SSE2SLOW; } if (rval & AV_CPU_FLAG_AVX) { if (ecx & 0x00000800) rval |= AV_CPU_FLAG_XOP; if (ecx & 0x00010000) rval |= AV_CPU_FLAG_FMA4; } } if (!strncmp(vendor.c, "GenuineIntel", 12)) { if (family == 6 && (model == 9 || model == 13 || model == 14)) { if (rval & AV_CPU_FLAG_SSE2) rval ^= AV_CPU_FLAG_SSE2SLOW | AV_CPU_FLAG_SSE2; if (rval & AV_CPU_FLAG_SSE3) rval ^= AV_CPU_FLAG_SSE3SLOW | AV_CPU_FLAG_SSE3; } if (family == 6 && model == 28) rval |= AV_CPU_FLAG_ATOM; } #endif return rval; }
1,485
1
int ff_h264_fill_default_ref_list ( H264Context * h ) { int i , len ; if ( h -> slice_type_nos == AV_PICTURE_TYPE_B ) { Picture * sorted [ 32 ] ; int cur_poc , list ; int lens [ 2 ] ; if ( FIELD_PICTURE ) cur_poc = h -> cur_pic_ptr -> field_poc [ h -> picture_structure == PICT_BOTTOM_FIELD ] ; else cur_poc = h -> cur_pic_ptr -> poc ; for ( list = 0 ; list < 2 ; list ++ ) { len = add_sorted ( sorted , h -> short_ref , h -> short_ref_count , cur_poc , 1 ^ list ) ; len += add_sorted ( sorted + len , h -> short_ref , h -> short_ref_count , cur_poc , 0 ^ list ) ; assert ( len <= 32 ) ; len = build_def_list ( h -> default_ref_list [ list ] , sorted , len , 0 , h -> picture_structure ) ; len += build_def_list ( h -> default_ref_list [ list ] + len , h -> long_ref , 16 , 1 , h -> picture_structure ) ; assert ( len <= 32 ) ; if ( len < h -> ref_count [ list ] ) memset ( & h -> default_ref_list [ list ] [ len ] , 0 , sizeof ( Picture ) * ( h -> ref_count [ list ] - len ) ) ; lens [ list ] = len ; } if ( lens [ 0 ] == lens [ 1 ] && lens [ 1 ] > 1 ) { for ( i = 0 ; h -> default_ref_list [ 0 ] [ i ] . f . data [ 0 ] == h -> default_ref_list [ 1 ] [ i ] . f . data [ 0 ] && i < lens [ 0 ] ; i ++ ) ; if ( i == lens [ 0 ] ) FFSWAP ( Picture , h -> default_ref_list [ 1 ] [ 0 ] , h -> default_ref_list [ 1 ] [ 1 ] ) ; } } else { len = build_def_list ( h -> default_ref_list [ 0 ] , h -> short_ref , h -> short_ref_count , 0 , h -> picture_structure ) ; len += build_def_list ( h -> default_ref_list [ 0 ] + len , h -> long_ref , 16 , 1 , h -> picture_structure ) ; assert ( len <= 32 ) ; if ( len < h -> ref_count [ 0 ] ) memset ( & h -> default_ref_list [ 0 ] [ len ] , 0 , sizeof ( Picture ) * ( h -> ref_count [ 0 ] - len ) ) ; } # ifdef TRACE for ( i = 0 ; i < h -> ref_count [ 0 ] ; i ++ ) { tprintf ( h -> avctx , "List0: %s fn:%d 0x%p\n" , ( h -> default_ref_list [ 0 ] [ i ] . long_ref ? "LT" : "ST" ) , h -> default_ref_list [ 0 ] [ i ] . pic_id , h -> default_ref_list [ 0 ] [ i ] . f . data [ 0 ] ) ; } if ( h -> slice_type_nos == AV_PICTURE_TYPE_B ) { for ( i = 0 ; i < h -> ref_count [ 1 ] ; i ++ ) { tprintf ( h -> avctx , "List1: %s fn:%d 0x%p\n" , ( h -> default_ref_list [ 1 ] [ i ] . long_ref ? "LT" : "ST" ) , h -> default_ref_list [ 1 ] [ i ] . pic_id , h -> default_ref_list [ 1 ] [ i ] . f . data [ 0 ] ) ; } } # endif return 0 ; }
int ff_h264_fill_default_ref_list ( H264Context * h ) { int i , len ; if ( h -> slice_type_nos == AV_PICTURE_TYPE_B ) { Picture * sorted [ 32 ] ; int cur_poc , list ; int lens [ 2 ] ; if ( FIELD_PICTURE ) cur_poc = h -> cur_pic_ptr -> field_poc [ h -> picture_structure == PICT_BOTTOM_FIELD ] ; else cur_poc = h -> cur_pic_ptr -> poc ; for ( list = 0 ; list < 2 ; list ++ ) { len = add_sorted ( sorted , h -> short_ref , h -> short_ref_count , cur_poc , 1 ^ list ) ; len += add_sorted ( sorted + len , h -> short_ref , h -> short_ref_count , cur_poc , 0 ^ list ) ; assert ( len <= 32 ) ; len = build_def_list ( h -> default_ref_list [ list ] , sorted , len , 0 , h -> picture_structure ) ; len += build_def_list ( h -> default_ref_list [ list ] + len , h -> long_ref , 16 , 1 , h -> picture_structure ) ; assert ( len <= 32 ) ; if ( len < h -> ref_count [ list ] ) memset ( & h -> default_ref_list [ list ] [ len ] , 0 , sizeof ( Picture ) * ( h -> ref_count [ list ] - len ) ) ; lens [ list ] = len ; } if ( lens [ 0 ] == lens [ 1 ] && lens [ 1 ] > 1 ) { for ( i = 0 ; h -> default_ref_list [ 0 ] [ i ] . f . data [ 0 ] == h -> default_ref_list [ 1 ] [ i ] . f . data [ 0 ] && i < lens [ 0 ] ; i ++ ) ; if ( i == lens [ 0 ] ) FFSWAP ( Picture , h -> default_ref_list [ 1 ] [ 0 ] , h -> default_ref_list [ 1 ] [ 1 ] ) ; } } else { len = build_def_list ( h -> default_ref_list [ 0 ] , h -> short_ref , h -> short_ref_count , 0 , h -> picture_structure ) ; len += build_def_list ( h -> default_ref_list [ 0 ] + len , h -> long_ref , 16 , 1 , h -> picture_structure ) ; assert ( len <= 32 ) ; if ( len < h -> ref_count [ 0 ] ) memset ( & h -> default_ref_list [ 0 ] [ len ] , 0 , sizeof ( Picture ) * ( h -> ref_count [ 0 ] - len ) ) ; } # ifdef TRACE for ( i = 0 ; i < h -> ref_count [ 0 ] ; i ++ ) { tprintf ( h -> avctx , "List0: %s fn:%d 0x%p\n" , ( h -> default_ref_list [ 0 ] [ i ] . long_ref ? "LT" : "ST" ) , h -> default_ref_list [ 0 ] [ i ] . pic_id , h -> default_ref_list [ 0 ] [ i ] . f . data [ 0 ] ) ; } if ( h -> slice_type_nos == AV_PICTURE_TYPE_B ) { for ( i = 0 ; i < h -> ref_count [ 1 ] ; i ++ ) { tprintf ( h -> avctx , "List1: %s fn:%d 0x%p\n" , ( h -> default_ref_list [ 1 ] [ i ] . long_ref ? "LT" : "ST" ) , h -> default_ref_list [ 1 ] [ i ] . pic_id , h -> default_ref_list [ 1 ] [ i ] . f . data [ 0 ] ) ; } } # endif return 0 ; }
1,486
1
static int inet6_fill_ifinfo(struct sk_buff *skb, struct inet6_dev *idev, u32 pid, u32 seq, int event, unsigned int flags) { struct net_device *dev = idev->dev; __s32 *array = NULL; struct ifinfomsg *r; struct nlmsghdr *nlh; unsigned char *b = skb->tail; struct rtattr *subattr; __u32 mtu = dev->mtu; struct ifla_cacheinfo ci; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*r), flags); r = NLMSG_DATA(nlh); r->ifi_family = AF_INET6; r->ifi_type = dev->type; r->ifi_index = dev->ifindex; r->ifi_flags = dev_get_flags(dev); r->ifi_change = 0; RTA_PUT(skb, IFLA_IFNAME, strlen(dev->name)+1, dev->name); if (dev->addr_len) RTA_PUT(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr); RTA_PUT(skb, IFLA_MTU, sizeof(mtu), &mtu); if (dev->ifindex != dev->iflink) RTA_PUT(skb, IFLA_LINK, sizeof(int), &dev->iflink); subattr = (struct rtattr*)skb->tail; RTA_PUT(skb, IFLA_PROTINFO, 0, NULL); /* return the device flags */ RTA_PUT(skb, IFLA_INET6_FLAGS, sizeof(__u32), &idev->if_flags); /* return interface cacheinfo */ ci.max_reasm_len = IPV6_MAXPLEN; ci.tstamp = (__u32)(TIME_DELTA(idev->tstamp, INITIAL_JIFFIES) / HZ * 100 + TIME_DELTA(idev->tstamp, INITIAL_JIFFIES) % HZ * 100 / HZ); ci.reachable_time = idev->nd_parms->reachable_time; ci.retrans_time = idev->nd_parms->retrans_time; RTA_PUT(skb, IFLA_INET6_CACHEINFO, sizeof(ci), &ci); /* return the device sysctl params */ if ((array = kmalloc(DEVCONF_MAX * sizeof(*array), GFP_ATOMIC)) == NULL) goto rtattr_failure; ipv6_store_devconf(&idev->cnf, array, DEVCONF_MAX * sizeof(*array)); RTA_PUT(skb, IFLA_INET6_CONF, DEVCONF_MAX * sizeof(*array), array); /* XXX - Statistics/MC not implemented */ subattr->rta_len = skb->tail - (u8*)subattr; nlh->nlmsg_len = skb->tail - b; kfree(array); return skb->len; nlmsg_failure: rtattr_failure: if (array) kfree(array); skb_trim(skb, b - skb->data); return -1; }
static int inet6_fill_ifinfo(struct sk_buff *skb, struct inet6_dev *idev, u32 pid, u32 seq, int event, unsigned int flags) { struct net_device *dev = idev->dev; __s32 *array = NULL; struct ifinfomsg *r; struct nlmsghdr *nlh; unsigned char *b = skb->tail; struct rtattr *subattr; __u32 mtu = dev->mtu; struct ifla_cacheinfo ci; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*r), flags); r = NLMSG_DATA(nlh); r->ifi_family = AF_INET6; r->ifi_type = dev->type; r->ifi_index = dev->ifindex; r->ifi_flags = dev_get_flags(dev); r->ifi_change = 0; RTA_PUT(skb, IFLA_IFNAME, strlen(dev->name)+1, dev->name); if (dev->addr_len) RTA_PUT(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr); RTA_PUT(skb, IFLA_MTU, sizeof(mtu), &mtu); if (dev->ifindex != dev->iflink) RTA_PUT(skb, IFLA_LINK, sizeof(int), &dev->iflink); subattr = (struct rtattr*)skb->tail; RTA_PUT(skb, IFLA_PROTINFO, 0, NULL); RTA_PUT(skb, IFLA_INET6_FLAGS, sizeof(__u32), &idev->if_flags); ci.max_reasm_len = IPV6_MAXPLEN; ci.tstamp = (__u32)(TIME_DELTA(idev->tstamp, INITIAL_JIFFIES) / HZ * 100 + TIME_DELTA(idev->tstamp, INITIAL_JIFFIES) % HZ * 100 / HZ); ci.reachable_time = idev->nd_parms->reachable_time; ci.retrans_time = idev->nd_parms->retrans_time; RTA_PUT(skb, IFLA_INET6_CACHEINFO, sizeof(ci), &ci); if ((array = kmalloc(DEVCONF_MAX * sizeof(*array), GFP_ATOMIC)) == NULL) goto rtattr_failure; ipv6_store_devconf(&idev->cnf, array, DEVCONF_MAX * sizeof(*array)); RTA_PUT(skb, IFLA_INET6_CONF, DEVCONF_MAX * sizeof(*array), array); subattr->rta_len = skb->tail - (u8*)subattr; nlh->nlmsg_len = skb->tail - b; kfree(array); return skb->len; nlmsg_failure: rtattr_failure: if (array) kfree(array); skb_trim(skb, b - skb->data); return -1; }
1,487
1
static void setAppend(SetType& set, const VariantType& v) { auto value_type = type(v); if (value_type != HPHP::serialize::Type::INT64 && value_type != HPHP::serialize::Type::STRING) { throw HPHP::serialize::UnserializeError( "Unsupported keyset element of type " + folly::to<std::string>(value_type)); } set.append(v); }
static void setAppend(SetType& set, const VariantType& v) { auto value_type = type(v); if (value_type != HPHP::serialize::Type::INT64 && value_type != HPHP::serialize::Type::STRING) { throw HPHP::serialize::UnserializeError( "Unsupported keyset element of type " + folly::to<std::string>(value_type)); } set.append(v); }
1,488
1
static void rose_loopback_timer(unsigned long param) { struct sk_buff *skb; struct net_device *dev; rose_address *dest; struct sock *sk; unsigned short frametype; unsigned int lci_i, lci_o; while ((skb = skb_dequeue(&loopback_queue)) != NULL) { lci_i = ((skb->data[0] << 8) & 0xF00) + ((skb->data[1] << 0) & 0x0FF); frametype = skb->data[2]; dest = (rose_address *)(skb->data + 4); lci_o = ROSE_DEFAULT_MAXVC + 1 - lci_i; skb_reset_transport_header(skb); sk = rose_find_socket(lci_o, rose_loopback_neigh); if (sk) { if (rose_process_rx_frame(sk, skb) == 0) kfree_skb(skb); continue; } if (frametype == ROSE_CALL_REQUEST) { if ((dev = rose_dev_get(dest)) != NULL) { if (rose_rx_call_request(skb, dev, rose_loopback_neigh, lci_o) == 0) kfree_skb(skb); } else { kfree_skb(skb); } } else { kfree_skb(skb); } } }
static void rose_loopback_timer(unsigned long param) { struct sk_buff *skb; struct net_device *dev; rose_address *dest; struct sock *sk; unsigned short frametype; unsigned int lci_i, lci_o; while ((skb = skb_dequeue(&loopback_queue)) != NULL) { lci_i = ((skb->data[0] << 8) & 0xF00) + ((skb->data[1] << 0) & 0x0FF); frametype = skb->data[2]; dest = (rose_address *)(skb->data + 4); lci_o = ROSE_DEFAULT_MAXVC + 1 - lci_i; skb_reset_transport_header(skb); sk = rose_find_socket(lci_o, rose_loopback_neigh); if (sk) { if (rose_process_rx_frame(sk, skb) == 0) kfree_skb(skb); continue; } if (frametype == ROSE_CALL_REQUEST) { if ((dev = rose_dev_get(dest)) != NULL) { if (rose_rx_call_request(skb, dev, rose_loopback_neigh, lci_o) == 0) kfree_skb(skb); } else { kfree_skb(skb); } } else { kfree_skb(skb); } } }
1,489
0
static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size) { GetBitContext gb; int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0; int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0; int dts_flag = -1, cts_flag = -1; int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE; init_get_bits(&gb, buf, buf_size*8); if (sl->use_au_start) au_start_flag = get_bits1(&gb); if (sl->use_au_end) au_end_flag = get_bits1(&gb); if (!sl->use_au_start && !sl->use_au_end) au_start_flag = au_end_flag = 1; if (sl->ocr_len > 0) ocr_flag = get_bits1(&gb); if (sl->use_idle) idle_flag = get_bits1(&gb); if (sl->use_padding) padding_flag = get_bits1(&gb); if (padding_flag) padding_bits = get_bits(&gb, 3); if (!idle_flag && (!padding_flag || padding_bits != 0)) { if (sl->packet_seq_num_len) skip_bits_long(&gb, sl->packet_seq_num_len); if (sl->degr_prior_len) if (get_bits1(&gb)) skip_bits(&gb, sl->degr_prior_len); if (ocr_flag) skip_bits_long(&gb, sl->ocr_len); if (au_start_flag) { if (sl->use_rand_acc_pt) get_bits1(&gb); if (sl->au_seq_num_len > 0) skip_bits_long(&gb, sl->au_seq_num_len); if (sl->use_timestamps) { dts_flag = get_bits1(&gb); cts_flag = get_bits1(&gb); } } if (sl->inst_bitrate_len) inst_bitrate_flag = get_bits1(&gb); if (dts_flag == 1) dts = get_bits64(&gb, sl->timestamp_len); if (cts_flag == 1) cts = get_bits64(&gb, sl->timestamp_len); if (sl->au_len > 0) skip_bits_long(&gb, sl->au_len); if (inst_bitrate_flag) skip_bits_long(&gb, sl->inst_bitrate_len); } if (dts != AV_NOPTS_VALUE) pes->dts = dts; if (cts != AV_NOPTS_VALUE) pes->pts = cts; avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res); return (get_bits_count(&gb) + 7) >> 3; }
static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size) { GetBitContext gb; int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0; int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0; int dts_flag = -1, cts_flag = -1; int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE; init_get_bits(&gb, buf, buf_size*8); if (sl->use_au_start) au_start_flag = get_bits1(&gb); if (sl->use_au_end) au_end_flag = get_bits1(&gb); if (!sl->use_au_start && !sl->use_au_end) au_start_flag = au_end_flag = 1; if (sl->ocr_len > 0) ocr_flag = get_bits1(&gb); if (sl->use_idle) idle_flag = get_bits1(&gb); if (sl->use_padding) padding_flag = get_bits1(&gb); if (padding_flag) padding_bits = get_bits(&gb, 3); if (!idle_flag && (!padding_flag || padding_bits != 0)) { if (sl->packet_seq_num_len) skip_bits_long(&gb, sl->packet_seq_num_len); if (sl->degr_prior_len) if (get_bits1(&gb)) skip_bits(&gb, sl->degr_prior_len); if (ocr_flag) skip_bits_long(&gb, sl->ocr_len); if (au_start_flag) { if (sl->use_rand_acc_pt) get_bits1(&gb); if (sl->au_seq_num_len > 0) skip_bits_long(&gb, sl->au_seq_num_len); if (sl->use_timestamps) { dts_flag = get_bits1(&gb); cts_flag = get_bits1(&gb); } } if (sl->inst_bitrate_len) inst_bitrate_flag = get_bits1(&gb); if (dts_flag == 1) dts = get_bits64(&gb, sl->timestamp_len); if (cts_flag == 1) cts = get_bits64(&gb, sl->timestamp_len); if (sl->au_len > 0) skip_bits_long(&gb, sl->au_len); if (inst_bitrate_flag) skip_bits_long(&gb, sl->inst_bitrate_len); } if (dts != AV_NOPTS_VALUE) pes->dts = dts; if (cts != AV_NOPTS_VALUE) pes->pts = cts; avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res); return (get_bits_count(&gb) + 7) >> 3; }
1,491
0
static enum AVHWDeviceType hw_device_match_type_in_name(const char *codec_name) { const char *type_name; enum AVHWDeviceType type; for (type = av_hwdevice_iterate_types(AV_HWDEVICE_TYPE_NONE); type != AV_HWDEVICE_TYPE_NONE; type = av_hwdevice_iterate_types(type)) { type_name = av_hwdevice_get_type_name(type); if (strstr(codec_name, type_name)) return type; } return AV_HWDEVICE_TYPE_NONE; }
static enum AVHWDeviceType hw_device_match_type_in_name(const char *codec_name) { const char *type_name; enum AVHWDeviceType type; for (type = av_hwdevice_iterate_types(AV_HWDEVICE_TYPE_NONE); type != AV_HWDEVICE_TYPE_NONE; type = av_hwdevice_iterate_types(type)) { type_name = av_hwdevice_get_type_name(type); if (strstr(codec_name, type_name)) return type; } return AV_HWDEVICE_TYPE_NONE; }
1,494
0
static int dissect_h245_GenericCapability ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) { # line 664 "../../asn1/h245/h245.cnf" void * priv_data = actx -> private_data ; actx -> private_data = gef_ctx_alloc ( NULL , "GenericCapability" ) ; offset = dissect_per_sequence ( tvb , offset , actx , tree , hf_index , ett_h245_GenericCapability , GenericCapability_sequence ) ; # line 667 "../../asn1/h245/h245.cnf" actx -> private_data = priv_data ; return offset ; }
static int dissect_h245_GenericCapability ( tvbuff_t * tvb _U_ , int offset _U_ , asn1_ctx_t * actx _U_ , proto_tree * tree _U_ , int hf_index _U_ ) { # line 664 "../../asn1/h245/h245.cnf" void * priv_data = actx -> private_data ; actx -> private_data = gef_ctx_alloc ( NULL , "GenericCapability" ) ; offset = dissect_per_sequence ( tvb , offset , actx , tree , hf_index , ett_h245_GenericCapability , GenericCapability_sequence ) ; # line 667 "../../asn1/h245/h245.cnf" actx -> private_data = priv_data ; return offset ; }
1,495
0
static void setAppend(SetType& set, const VariantType& v) { if (!v.isInteger() && !v.isString()) { throw HPHP::serialize::UnserializeError( "Keysets can only contain integers or strings" ); } set.append(v); }
static void setAppend(SetType& set, const VariantType& v) { if (!v.isInteger() && !v.isString()) { throw HPHP::serialize::UnserializeError( "Keysets can only contain integers or strings" ); } set.append(v); }
1,496
1
static __inline__ int cbq_dump_police(struct sk_buff *skb, struct cbq_class *cl) { unsigned char *b = skb->tail; struct tc_cbq_police opt; if (cl->police) { opt.police = cl->police; RTA_PUT(skb, TCA_CBQ_POLICE, sizeof(opt), &opt); } return skb->len; rtattr_failure: skb_trim(skb, b - skb->data); return -1; }
static __inline__ int cbq_dump_police(struct sk_buff *skb, struct cbq_class *cl) { unsigned char *b = skb->tail; struct tc_cbq_police opt; if (cl->police) { opt.police = cl->police; RTA_PUT(skb, TCA_CBQ_POLICE, sizeof(opt), &opt); } return skb->len; rtattr_failure: skb_trim(skb, b - skb->data); return -1; }
1,497
0
static void dumpcffheader ( FILE * cfff ) { putc ( '\1' , cfff ) ; putc ( '\0' , cfff ) ; putc ( '\4' , cfff ) ; putc ( '\4' , cfff ) ; }
static void dumpcffheader ( FILE * cfff ) { putc ( '\1' , cfff ) ; putc ( '\0' , cfff ) ; putc ( '\4' , cfff ) ; putc ( '\4' , cfff ) ; }
1,498
0
bool VariableUnserializer::matchString(folly::StringPiece str) { const char* p = m_buf; assertx(p <= m_end); int total = 0; if (*p == 'S' && type() == VariableUnserializer::Type::APCSerialize) { total = 2 + 8 + 1; if (p + total > m_end) return false; p++; if (*p++ != ':') return false; auto const sd = *reinterpret_cast<StringData*const*>(p); assertx(sd->isStatic()); if (str.compare(sd->slice()) != 0) return false; p += size_t(8); } else { const auto ss = str.size(); if (ss >= 100) return false; int digits = ss >= 10 ? 2 : 1; total = 2 + digits + 2 + ss + 2; if (p + total > m_end) return false; if (*p++ != 's') return false; if (*p++ != ':') return false; if (digits == 2) { if (*p++ != '0' + ss/10) return false; if (*p++ != '0' + ss%10) return false; } else { if (*p++ != '0' + ss) return false; } if (*p++ != ':') return false; if (*p++ != '\"') return false; if (memcmp(p, str.data(), ss)) return false; p += ss; if (*p++ != '\"') return false; } if (*p++ != ';') return false; assertx(m_buf + total == p); m_buf = p; return true; }
bool VariableUnserializer::matchString(folly::StringPiece str) { const char* p = m_buf; assertx(p <= m_end); int total = 0; if (*p == 'S' && type() == VariableUnserializer::Type::APCSerialize) { total = 2 + 8 + 1; if (p + total > m_end) return false; p++; if (*p++ != ':') return false; auto const sd = *reinterpret_cast<StringData*const*>(p); assertx(sd->isStatic()); if (str.compare(sd->slice()) != 0) return false; p += size_t(8); } else { const auto ss = str.size(); if (ss >= 100) return false; int digits = ss >= 10 ? 2 : 1; total = 2 + digits + 2 + ss + 2; if (p + total > m_end) return false; if (*p++ != 's') return false; if (*p++ != ':') return false; if (digits == 2) { if (*p++ != '0' + ss/10) return false; if (*p++ != '0' + ss%10) return false; } else { if (*p++ != '0' + ss) return false; } if (*p++ != ':') return false; if (*p++ != '\"') return false; if (memcmp(p, str.data(), ss)) return false; p += ss; if (*p++ != '\"') return false; } if (*p++ != ';') return false; assertx(m_buf + total == p); m_buf = p; return true; }
1,499
1
tca_get_fill(struct sk_buff *skb, struct tc_action *a, u32 pid, u32 seq, u16 flags, int event, int bind, int ref) { struct tcamsg *t; struct nlmsghdr *nlh; unsigned char *b = skb->tail; struct rtattr *x; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*t), flags); t = NLMSG_DATA(nlh); t->tca_family = AF_UNSPEC; x = (struct rtattr*) skb->tail; RTA_PUT(skb, TCA_ACT_TAB, 0, NULL); if (tcf_action_dump(skb, a, bind, ref) < 0) goto rtattr_failure; x->rta_len = skb->tail - (u8*)x; nlh->nlmsg_len = skb->tail - b; return skb->len; rtattr_failure: nlmsg_failure: skb_trim(skb, b - skb->data); return -1; }
tca_get_fill(struct sk_buff *skb, struct tc_action *a, u32 pid, u32 seq, u16 flags, int event, int bind, int ref) { struct tcamsg *t; struct nlmsghdr *nlh; unsigned char *b = skb->tail; struct rtattr *x; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*t), flags); t = NLMSG_DATA(nlh); t->tca_family = AF_UNSPEC; x = (struct rtattr*) skb->tail; RTA_PUT(skb, TCA_ACT_TAB, 0, NULL); if (tcf_action_dump(skb, a, bind, ref) < 0) goto rtattr_failure; x->rta_len = skb->tail - (u8*)x; nlh->nlmsg_len = skb->tail - b; return skb->len; rtattr_failure: nlmsg_failure: skb_trim(skb, b - skb->data); return -1; }
1,500
0
static av_cold int encode_close(AVCodecContext* avc_context) { TheoraContext *h = avc_context->priv_data; th_encode_free(h->t_state); av_freep(&h->stats); av_freep(&avc_context->coded_frame); av_freep(&avc_context->stats_out); av_freep(&avc_context->extradata); avc_context->extradata_size = 0; return 0; }
static av_cold int encode_close(AVCodecContext* avc_context) { TheoraContext *h = avc_context->priv_data; th_encode_free(h->t_state); av_freep(&h->stats); av_freep(&avc_context->coded_frame); av_freep(&avc_context->stats_out); av_freep(&avc_context->extradata); avc_context->extradata_size = 0; return 0; }
1,501
1
tc_dump_action(struct sk_buff *skb, struct netlink_callback *cb) { struct nlmsghdr *nlh; unsigned char *b = skb->tail; struct rtattr *x; struct tc_action_ops *a_o; struct tc_action a; int ret = 0; struct tcamsg *t = (struct tcamsg *) NLMSG_DATA(cb->nlh); char *kind = find_dump_kind(cb->nlh); if (kind == NULL) { printk("tc_dump_action: action bad kind\n"); return 0; } a_o = tc_lookup_action_n(kind); if (a_o == NULL) { printk("failed to find %s\n", kind); return 0; } memset(&a, 0, sizeof(struct tc_action)); a.ops = a_o; if (a_o->walk == NULL) { printk("tc_dump_action: %s !capable of dumping table\n", kind); goto rtattr_failure; } nlh = NLMSG_PUT(skb, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, cb->nlh->nlmsg_type, sizeof(*t)); t = NLMSG_DATA(nlh); t->tca_family = AF_UNSPEC; x = (struct rtattr *) skb->tail; RTA_PUT(skb, TCA_ACT_TAB, 0, NULL); ret = a_o->walk(skb, cb, RTM_GETACTION, &a); if (ret < 0) goto rtattr_failure; if (ret > 0) { x->rta_len = skb->tail - (u8 *) x; ret = skb->len; } else skb_trim(skb, (u8*)x - skb->data); nlh->nlmsg_len = skb->tail - b; if (NETLINK_CB(cb->skb).pid && ret) nlh->nlmsg_flags |= NLM_F_MULTI; module_put(a_o->owner); return skb->len; rtattr_failure: nlmsg_failure: module_put(a_o->owner); skb_trim(skb, b - skb->data); return skb->len; }
tc_dump_action(struct sk_buff *skb, struct netlink_callback *cb) { struct nlmsghdr *nlh; unsigned char *b = skb->tail; struct rtattr *x; struct tc_action_ops *a_o; struct tc_action a; int ret = 0; struct tcamsg *t = (struct tcamsg *) NLMSG_DATA(cb->nlh); char *kind = find_dump_kind(cb->nlh); if (kind == NULL) { printk("tc_dump_action: action bad kind\n"); return 0; } a_o = tc_lookup_action_n(kind); if (a_o == NULL) { printk("failed to find %s\n", kind); return 0; } memset(&a, 0, sizeof(struct tc_action)); a.ops = a_o; if (a_o->walk == NULL) { printk("tc_dump_action: %s !capable of dumping table\n", kind); goto rtattr_failure; } nlh = NLMSG_PUT(skb, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, cb->nlh->nlmsg_type, sizeof(*t)); t = NLMSG_DATA(nlh); t->tca_family = AF_UNSPEC; x = (struct rtattr *) skb->tail; RTA_PUT(skb, TCA_ACT_TAB, 0, NULL); ret = a_o->walk(skb, cb, RTM_GETACTION, &a); if (ret < 0) goto rtattr_failure; if (ret > 0) { x->rta_len = skb->tail - (u8 *) x; ret = skb->len; } else skb_trim(skb, (u8*)x - skb->data); nlh->nlmsg_len = skb->tail - b; if (NETLINK_CB(cb->skb).pid && ret) nlh->nlmsg_flags |= NLM_F_MULTI; module_put(a_o->owner); return skb->len; rtattr_failure: nlmsg_failure: module_put(a_o->owner); skb_trim(skb, b - skb->data); return skb->len; }
1,502
1
bool VariableUnserializer::matchString(folly::StringPiece str) { const char* p = m_buf; assertx(p <= m_end); int total = 0; if (*p == 'S') { total = 2 + 8 + 1; if (p + total > m_end) return false; p++; if (*p++ != ':') return false; auto const sd = *reinterpret_cast<StringData*const*>(p); assertx(sd->isStatic()); if (str.compare(sd->slice()) != 0) return false; p += size_t(8); } else { const auto ss = str.size(); if (ss >= 100) return false; int digits = ss >= 10 ? 2 : 1; total = 2 + digits + 2 + ss + 2; if (p + total > m_end) return false; if (*p++ != 's') return false; if (*p++ != ':') return false; if (digits == 2) { if (*p++ != '0' + ss/10) return false; if (*p++ != '0' + ss%10) return false; } else { if (*p++ != '0' + ss) return false; } if (*p++ != ':') return false; if (*p++ != '\"') return false; if (memcmp(p, str.data(), ss)) return false; p += ss; if (*p++ != '\"') return false; } if (*p++ != ';') return false; assertx(m_buf + total == p); m_buf = p; return true; }
bool VariableUnserializer::matchString(folly::StringPiece str) { const char* p = m_buf; assertx(p <= m_end); int total = 0; if (*p == 'S') { total = 2 + 8 + 1; if (p + total > m_end) return false; p++; if (*p++ != ':') return false; auto const sd = *reinterpret_cast<StringData*const*>(p); assertx(sd->isStatic()); if (str.compare(sd->slice()) != 0) return false; p += size_t(8); } else { const auto ss = str.size(); if (ss >= 100) return false; int digits = ss >= 10 ? 2 : 1; total = 2 + digits + 2 + ss + 2; if (p + total > m_end) return false; if (*p++ != 's') return false; if (*p++ != ':') return false; if (digits == 2) { if (*p++ != '0' + ss/10) return false; if (*p++ != '0' + ss%10) return false; } else { if (*p++ != '0' + ss) return false; } if (*p++ != ':') return false; if (*p++ != '\"') return false; if (memcmp(p, str.data(), ss)) return false; p += ss; if (*p++ != '\"') return false; } if (*p++ != ';') return false; assertx(m_buf + total == p); m_buf = p; return true; }
1,503
0
static void destroy_int_fifo ( int_fifo * fifo ) { int_node * i_n ; if ( fifo != NULL ) { do { UNLINK_FIFO ( i_n , * fifo , link ) ; if ( i_n != NULL ) free ( i_n ) ; } while ( i_n != NULL ) ; free ( fifo ) ; } }
static void destroy_int_fifo ( int_fifo * fifo ) { int_node * i_n ; if ( fifo != NULL ) { do { UNLINK_FIFO ( i_n , * fifo , link ) ; if ( i_n != NULL ) free ( i_n ) ; } while ( i_n != NULL ) ; free ( fifo ) ; } }
1,504
0
static int vaapi_encode_h264_init_slice_params(AVCodecContext *avctx, VAAPIEncodePicture *pic, VAAPIEncodeSlice *slice) { VAAPIEncodeContext *ctx = avctx->priv_data; VAEncSequenceParameterBufferH264 *vseq = ctx->codec_sequence_params; VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params; VAEncSliceParameterBufferH264 *vslice = slice->codec_slice_params; VAAPIEncodeH264Context *priv = ctx->priv_data; VAAPIEncodeH264Slice *pslice; VAAPIEncodeH264MiscSliceParams *mslice; int i; slice->priv_data = av_mallocz(sizeof(*pslice)); if (!slice->priv_data) return AVERROR(ENOMEM); pslice = slice->priv_data; mslice = &pslice->misc_slice_params; if (pic->type == PICTURE_TYPE_IDR) mslice->nal_unit_type = H264_NAL_IDR_SLICE; else mslice->nal_unit_type = H264_NAL_SLICE; switch (pic->type) { case PICTURE_TYPE_IDR: vslice->slice_type = SLICE_TYPE_I; mslice->nal_ref_idc = 3; break; case PICTURE_TYPE_I: vslice->slice_type = SLICE_TYPE_I; mslice->nal_ref_idc = 2; break; case PICTURE_TYPE_P: vslice->slice_type = SLICE_TYPE_P; mslice->nal_ref_idc = 1; break; case PICTURE_TYPE_B: vslice->slice_type = SLICE_TYPE_B; mslice->nal_ref_idc = 0; break; default: av_assert0(0 && "invalid picture type"); } // Only one slice per frame. vslice->macroblock_address = 0; vslice->num_macroblocks = priv->mb_width * priv->mb_height; vslice->macroblock_info = VA_INVALID_ID; vslice->pic_parameter_set_id = vpic->pic_parameter_set_id; vslice->idr_pic_id = priv->idr_pic_count++; vslice->pic_order_cnt_lsb = pic->display_order & ((1 << (4 + vseq->seq_fields.bits.log2_max_pic_order_cnt_lsb_minus4)) - 1); for (i = 0; i < FF_ARRAY_ELEMS(vslice->RefPicList0); i++) { vslice->RefPicList0[i].picture_id = VA_INVALID_ID; vslice->RefPicList0[i].flags = VA_PICTURE_H264_INVALID; vslice->RefPicList1[i].picture_id = VA_INVALID_ID; vslice->RefPicList1[i].flags = VA_PICTURE_H264_INVALID; } av_assert0(pic->nb_refs <= 2); if (pic->nb_refs >= 1) { // Backward reference for P- or B-frame. av_assert0(pic->type == PICTURE_TYPE_P || pic->type == PICTURE_TYPE_B); vslice->num_ref_idx_l0_active_minus1 = 0; vslice->RefPicList0[0] = vpic->ReferenceFrames[0]; } if (pic->nb_refs >= 2) { // Forward reference for B-frame. av_assert0(pic->type == PICTURE_TYPE_B); vslice->num_ref_idx_l1_active_minus1 = 0; vslice->RefPicList1[0] = vpic->ReferenceFrames[1]; } if (pic->type == PICTURE_TYPE_B) vslice->slice_qp_delta = priv->fixed_qp_b - vpic->pic_init_qp; else if (pic->type == PICTURE_TYPE_P) vslice->slice_qp_delta = priv->fixed_qp_p - vpic->pic_init_qp; else vslice->slice_qp_delta = priv->fixed_qp_idr - vpic->pic_init_qp; vslice->direct_spatial_mv_pred_flag = 1; return 0; }
static int vaapi_encode_h264_init_slice_params(AVCodecContext *avctx, VAAPIEncodePicture *pic, VAAPIEncodeSlice *slice) { VAAPIEncodeContext *ctx = avctx->priv_data; VAEncSequenceParameterBufferH264 *vseq = ctx->codec_sequence_params; VAEncPictureParameterBufferH264 *vpic = pic->codec_picture_params; VAEncSliceParameterBufferH264 *vslice = slice->codec_slice_params; VAAPIEncodeH264Context *priv = ctx->priv_data; VAAPIEncodeH264Slice *pslice; VAAPIEncodeH264MiscSliceParams *mslice; int i; slice->priv_data = av_mallocz(sizeof(*pslice)); if (!slice->priv_data) return AVERROR(ENOMEM); pslice = slice->priv_data; mslice = &pslice->misc_slice_params; if (pic->type == PICTURE_TYPE_IDR) mslice->nal_unit_type = H264_NAL_IDR_SLICE; else mslice->nal_unit_type = H264_NAL_SLICE; switch (pic->type) { case PICTURE_TYPE_IDR: vslice->slice_type = SLICE_TYPE_I; mslice->nal_ref_idc = 3; break; case PICTURE_TYPE_I: vslice->slice_type = SLICE_TYPE_I; mslice->nal_ref_idc = 2; break; case PICTURE_TYPE_P: vslice->slice_type = SLICE_TYPE_P; mslice->nal_ref_idc = 1; break; case PICTURE_TYPE_B: vslice->slice_type = SLICE_TYPE_B; mslice->nal_ref_idc = 0; break; default: av_assert0(0 && "invalid picture type"); }
1,505
0
Array& ObjectData::reserveProperties(int numDynamic /* = 2 */) { if (getAttribute(HasDynPropArr)) { return dynPropArray(); } auto const allocsz = MixedArray::computeAllocBytesFromMaxElms(numDynamic); if (UNLIKELY(allocsz > kMaxSmallSize && tl_heap->preAllocOOM(allocsz))) { check_non_safepoint_surprise(); } return setDynPropArray( Array::attach(MixedArray::MakeReserveMixed(numDynamic)) ); }
Array& ObjectData::reserveProperties(int numDynamic ) { if (getAttribute(HasDynPropArr)) { return dynPropArray(); } auto const allocsz = MixedArray::computeAllocBytesFromMaxElms(numDynamic); if (UNLIKELY(allocsz > kMaxSmallSize && tl_heap->preAllocOOM(allocsz))) { check_non_safepoint_surprise(); } return setDynPropArray( Array::attach(MixedArray::MakeReserveMixed(numDynamic)) ); }
1,506
0
static char *assign_name(NetClientState *nc1, const char *model) { NetClientState *nc; char buf[256]; int id = 0; QTAILQ_FOREACH(nc, &net_clients, next) { if (nc == nc1) { continue; } /* For compatibility only bump id for net clients on a vlan */ if (strcmp(nc->model, model) == 0 && net_hub_id_for_client(nc, NULL) == 0) { id++; } } snprintf(buf, sizeof(buf), "%s.%d", model, id); return g_strdup(buf); }
static char *assign_name(NetClientState *nc1, const char *model) { NetClientState *nc; char buf[256]; int id = 0; QTAILQ_FOREACH(nc, &net_clients, next) { if (nc == nc1) { continue; } if (strcmp(nc->model, model) == 0 && net_hub_id_for_client(nc, NULL) == 0) { id++; } } snprintf(buf, sizeof(buf), "%s.%d", model, id); return g_strdup(buf); }
1,507
1
static int rtnetlink_fill_ifinfo(struct sk_buff *skb, struct net_device *dev, int type, u32 pid, u32 seq, u32 change, unsigned int flags) { struct ifinfomsg *r; struct nlmsghdr *nlh; unsigned char *b = skb->tail; nlh = NLMSG_NEW(skb, pid, seq, type, sizeof(*r), flags); r = NLMSG_DATA(nlh); r->ifi_family = AF_UNSPEC; r->ifi_type = dev->type; r->ifi_index = dev->ifindex; r->ifi_flags = dev_get_flags(dev); r->ifi_change = change; RTA_PUT(skb, IFLA_IFNAME, strlen(dev->name)+1, dev->name); if (1) { u32 txqlen = dev->tx_queue_len; RTA_PUT(skb, IFLA_TXQLEN, sizeof(txqlen), &txqlen); } if (1) { u32 weight = dev->weight; RTA_PUT(skb, IFLA_WEIGHT, sizeof(weight), &weight); } if (1) { struct rtnl_link_ifmap map = { .mem_start = dev->mem_start, .mem_end = dev->mem_end, .base_addr = dev->base_addr, .irq = dev->irq, .dma = dev->dma, .port = dev->if_port, }; RTA_PUT(skb, IFLA_MAP, sizeof(map), &map); } if (dev->addr_len) { RTA_PUT(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr); RTA_PUT(skb, IFLA_BROADCAST, dev->addr_len, dev->broadcast); } if (1) { u32 mtu = dev->mtu; RTA_PUT(skb, IFLA_MTU, sizeof(mtu), &mtu); } if (dev->ifindex != dev->iflink) { u32 iflink = dev->iflink; RTA_PUT(skb, IFLA_LINK, sizeof(iflink), &iflink); } if (dev->qdisc_sleeping) RTA_PUT(skb, IFLA_QDISC, strlen(dev->qdisc_sleeping->ops->id) + 1, dev->qdisc_sleeping->ops->id); if (dev->master) { u32 master = dev->master->ifindex; RTA_PUT(skb, IFLA_MASTER, sizeof(master), &master); } if (dev->get_stats) { unsigned long *stats = (unsigned long*)dev->get_stats(dev); if (stats) { struct rtattr *a; __u32 *s; int i; int n = sizeof(struct rtnl_link_stats)/4; a = __RTA_PUT(skb, IFLA_STATS, n*4); s = RTA_DATA(a); for (i=0; i<n; i++) s[i] = stats[i]; } } nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: rtattr_failure: skb_trim(skb, b - skb->data); return -1; }
static int rtnetlink_fill_ifinfo(struct sk_buff *skb, struct net_device *dev, int type, u32 pid, u32 seq, u32 change, unsigned int flags) { struct ifinfomsg *r; struct nlmsghdr *nlh; unsigned char *b = skb->tail; nlh = NLMSG_NEW(skb, pid, seq, type, sizeof(*r), flags); r = NLMSG_DATA(nlh); r->ifi_family = AF_UNSPEC; r->ifi_type = dev->type; r->ifi_index = dev->ifindex; r->ifi_flags = dev_get_flags(dev); r->ifi_change = change; RTA_PUT(skb, IFLA_IFNAME, strlen(dev->name)+1, dev->name); if (1) { u32 txqlen = dev->tx_queue_len; RTA_PUT(skb, IFLA_TXQLEN, sizeof(txqlen), &txqlen); } if (1) { u32 weight = dev->weight; RTA_PUT(skb, IFLA_WEIGHT, sizeof(weight), &weight); } if (1) { struct rtnl_link_ifmap map = { .mem_start = dev->mem_start, .mem_end = dev->mem_end, .base_addr = dev->base_addr, .irq = dev->irq, .dma = dev->dma, .port = dev->if_port, }; RTA_PUT(skb, IFLA_MAP, sizeof(map), &map); } if (dev->addr_len) { RTA_PUT(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr); RTA_PUT(skb, IFLA_BROADCAST, dev->addr_len, dev->broadcast); } if (1) { u32 mtu = dev->mtu; RTA_PUT(skb, IFLA_MTU, sizeof(mtu), &mtu); } if (dev->ifindex != dev->iflink) { u32 iflink = dev->iflink; RTA_PUT(skb, IFLA_LINK, sizeof(iflink), &iflink); } if (dev->qdisc_sleeping) RTA_PUT(skb, IFLA_QDISC, strlen(dev->qdisc_sleeping->ops->id) + 1, dev->qdisc_sleeping->ops->id); if (dev->master) { u32 master = dev->master->ifindex; RTA_PUT(skb, IFLA_MASTER, sizeof(master), &master); } if (dev->get_stats) { unsigned long *stats = (unsigned long*)dev->get_stats(dev); if (stats) { struct rtattr *a; __u32 *s; int i; int n = sizeof(struct rtnl_link_stats)/4; a = __RTA_PUT(skb, IFLA_STATS, n*4); s = RTA_DATA(a); for (i=0; i<n; i++) s[i] = stats[i]; } } nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: rtattr_failure: skb_trim(skb, b - skb->data); return -1; }
1,508
0
void VariableUnserializer::unserializeProp(ObjectData* obj, const String& key, Class* ctx, const String& realKey, int nProp) { auto const cls = obj->getVMClass(); auto const lookup = cls->getDeclPropSlot(ctx, key.get()); auto const slot = lookup.slot; tv_lval t; if (slot == kInvalidSlot || !lookup.accessible) { // Unserialize as a dynamic property. If this is the first, we need to // pre-allocate space in the array to ensure the elements don't move during // unserialization. obj->reserveDynProps(nProp); t = obj->makeDynProp(realKey.get()); } else { // We'll check if this doesn't violate the type-hint once we're done // unserializing all the props. t = obj->getPropLval(ctx, key.get()); } unserializePropertyValue(t, nProp); if (!RuntimeOption::RepoAuthoritative) return; if (!Repo::get().global().HardPrivatePropInference) return; /* * We assume for performance reasons in repo authoriative mode that * we can see all the sets to private properties in a class. * * It's a hole in this if we don't check unserialization doesn't * violate what we've seen, which we handle by throwing if the repo * was built with this option. */ if (UNLIKELY(slot == kInvalidSlot)) return; auto const repoTy = cls->declPropRepoAuthType(slot); if (LIKELY(tvMatchesRepoAuthType(*t, repoTy))) return; if (t.type() == KindOfUninit && (cls->declProperties()[slot].attrs & AttrLateInit)) { return; } throwUnexpectedType(key, obj, *t); }
void VariableUnserializer::unserializeProp(ObjectData* obj, const String& key, Class* ctx, const String& realKey, int nProp) { auto const cls = obj->getVMClass(); auto const lookup = cls->getDeclPropSlot(ctx, key.get()); auto const slot = lookup.slot; tv_lval t; if (slot == kInvalidSlot || !lookup.accessible) { obj->reserveDynProps(nProp); t = obj->makeDynProp(realKey.get()); } else { t = obj->getPropLval(ctx, key.get()); } unserializePropertyValue(t, nProp); if (!RuntimeOption::RepoAuthoritative) return; if (!Repo::get().global().HardPrivatePropInference) return; if (UNLIKELY(slot == kInvalidSlot)) return; auto const repoTy = cls->declPropRepoAuthType(slot); if (LIKELY(tvMatchesRepoAuthType(*t, repoTy))) return; if (t.type() == KindOfUninit && (cls->declProperties()[slot].attrs & AttrLateInit)) { return; } throwUnexpectedType(key, obj, *t); }
1,509
0
static void qemu_cpu_kick_thread ( CPUState * cpu ) { # ifndef _WIN32 int err ; err = pthread_kill ( cpu -> thread -> thread , SIG_IPI ) ; if ( err ) { fprintf ( stderr , "qemu:%s: %s" , __func__ , strerror ( err ) ) ; exit ( 1 ) ; } # else if ( ! qemu_cpu_is_self ( cpu ) ) { CONTEXT tcgContext ; if ( SuspendThread ( cpu -> hThread ) == ( DWORD ) - 1 ) { fprintf ( stderr , "qemu:%s: GetLastError:%lu\n" , __func__ , GetLastError ( ) ) ; exit ( 1 ) ; } tcgContext . ContextFlags = CONTEXT_CONTROL ; while ( GetThreadContext ( cpu -> hThread , & tcgContext ) != 0 ) { continue ; } cpu_signal ( 0 ) ; if ( ResumeThread ( cpu -> hThread ) == ( DWORD ) - 1 ) { fprintf ( stderr , "qemu:%s: GetLastError:%lu\n" , __func__ , GetLastError ( ) ) ; exit ( 1 ) ; } } # endif }
static void qemu_cpu_kick_thread ( CPUState * cpu ) { # ifndef _WIN32 int err ; err = pthread_kill ( cpu -> thread -> thread , SIG_IPI ) ; if ( err ) { fprintf ( stderr , "qemu:%s: %s" , __func__ , strerror ( err ) ) ; exit ( 1 ) ; } # else if ( ! qemu_cpu_is_self ( cpu ) ) { CONTEXT tcgContext ; if ( SuspendThread ( cpu -> hThread ) == ( DWORD ) - 1 ) { fprintf ( stderr , "qemu:%s: GetLastError:%lu\n" , __func__ , GetLastError ( ) ) ; exit ( 1 ) ; } tcgContext . ContextFlags = CONTEXT_CONTROL ; while ( GetThreadContext ( cpu -> hThread , & tcgContext ) != 0 ) { continue ; } cpu_signal ( 0 ) ; if ( ResumeThread ( cpu -> hThread ) == ( DWORD ) - 1 ) { fprintf ( stderr , "qemu:%s: GetLastError:%lu\n" , __func__ , GetLastError ( ) ) ; exit ( 1 ) ; } } # endif }
1,510
0
static void nbd_accept(void *opaque) { int server_fd = (uintptr_t) opaque; struct sockaddr_in addr; socklen_t addr_len = sizeof(addr); int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len); nbd_started = true; if (fd >= 0 && nbd_client_new(exp, fd, nbd_client_closed)) { nb_fds++; } }
static void nbd_accept(void *opaque) { int server_fd = (uintptr_t) opaque; struct sockaddr_in addr; socklen_t addr_len = sizeof(addr); int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len); nbd_started = true; if (fd >= 0 && nbd_client_new(exp, fd, nbd_client_closed)) { nb_fds++; } }
1,511
0
static void dma_init2(struct dma_cont *d, int base, int dshift, int page_base, int pageh_base, qemu_irq *cpu_request_exit) { int i; d->dshift = dshift; d->cpu_request_exit = cpu_request_exit; memory_region_init_io(&d->channel_io, NULL, &channel_io_ops, d, "dma-chan", 8 << d->dshift); memory_region_add_subregion(isa_address_space_io(NULL), base, &d->channel_io); isa_register_portio_list(NULL, page_base, page_portio_list, d, "dma-page"); if (pageh_base >= 0) { isa_register_portio_list(NULL, pageh_base, pageh_portio_list, d, "dma-pageh"); } memory_region_init_io(&d->cont_io, NULL, &cont_io_ops, d, "dma-cont", 8 << d->dshift); memory_region_add_subregion(isa_address_space_io(NULL), base + (8 << d->dshift), &d->cont_io); qemu_register_reset(dma_reset, d); dma_reset(d); for (i = 0; i < ARRAY_SIZE (d->regs); ++i) { d->regs[i].transfer_handler = dma_phony_handler; } }
static void dma_init2(struct dma_cont *d, int base, int dshift, int page_base, int pageh_base, qemu_irq *cpu_request_exit) { int i; d->dshift = dshift; d->cpu_request_exit = cpu_request_exit; memory_region_init_io(&d->channel_io, NULL, &channel_io_ops, d, "dma-chan", 8 << d->dshift); memory_region_add_subregion(isa_address_space_io(NULL), base, &d->channel_io); isa_register_portio_list(NULL, page_base, page_portio_list, d, "dma-page"); if (pageh_base >= 0) { isa_register_portio_list(NULL, pageh_base, pageh_portio_list, d, "dma-pageh"); } memory_region_init_io(&d->cont_io, NULL, &cont_io_ops, d, "dma-cont", 8 << d->dshift); memory_region_add_subregion(isa_address_space_io(NULL), base + (8 << d->dshift), &d->cont_io); qemu_register_reset(dma_reset, d); dma_reset(d); for (i = 0; i < ARRAY_SIZE (d->regs); ++i) { d->regs[i].transfer_handler = dma_phony_handler; } }
1,513
1
void PCRECache::dump(const std::string& filename) { std::ofstream out(filename.c_str()); switch (m_kind) { case CacheKind::Static: for (auto& it : *m_staticCache) { out << it.first->data() << "\n"; } break; case CacheKind::Lru: case CacheKind::Scalable: { std::vector<LRUCacheKey> keys; if (m_kind == CacheKind::Lru) { m_lruCache->snapshotKeys(keys); } else { m_scalableCache->snapshotKeys(keys); } for (auto& key: keys) { out << key.c_str() << "\n"; } } break; } out.close(); }
void PCRECache::dump(const std::string& filename) { std::ofstream out(filename.c_str()); switch (m_kind) { case CacheKind::Static: for (auto& it : *m_staticCache) { out << it.first->data() << "\n"; } break; case CacheKind::Lru: case CacheKind::Scalable: { std::vector<LRUCacheKey> keys; if (m_kind == CacheKind::Lru) { m_lruCache->snapshotKeys(keys); } else { m_scalableCache->snapshotKeys(keys); } for (auto& key: keys) { out << key.c_str() << "\n"; } } break; } out.close(); }
1,515
1
static inline int rtnetlink_fill_iwinfo(struct sk_buff * skb, struct net_device * dev, int type, char * event, int event_len) { struct ifinfomsg *r; struct nlmsghdr *nlh; unsigned char *b = skb->tail; nlh = NLMSG_PUT(skb, 0, 0, type, sizeof(*r)); r = NLMSG_DATA(nlh); r->ifi_family = AF_UNSPEC; r->ifi_type = dev->type; r->ifi_index = dev->ifindex; r->ifi_flags = dev->flags; r->ifi_change = 0; /* Wireless changes don't affect those flags */ /* Add the wireless events in the netlink packet */ RTA_PUT(skb, IFLA_WIRELESS, event_len, event); nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: rtattr_failure: skb_trim(skb, b - skb->data); return -1; }
static inline int rtnetlink_fill_iwinfo(struct sk_buff * skb, struct net_device * dev, int type, char * event, int event_len) { struct ifinfomsg *r; struct nlmsghdr *nlh; unsigned char *b = skb->tail; nlh = NLMSG_PUT(skb, 0, 0, type, sizeof(*r)); r = NLMSG_DATA(nlh); r->ifi_family = AF_UNSPEC; r->ifi_type = dev->type; r->ifi_index = dev->ifindex; r->ifi_flags = dev->flags; r->ifi_change = 0; RTA_PUT(skb, IFLA_WIRELESS, event_len, event); nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: rtattr_failure: skb_trim(skb, b - skb->data); return -1; }
1,516
0
void PCRECache::dump(folly::File& file) { switch (m_kind) { case CacheKind::Static: for (auto& it : *m_staticCache) { folly::writeFull(file.fd(), it.first->data(), it.first->size()); folly::writeFull(file.fd(), "\n", 1); } break; case CacheKind::Lru: case CacheKind::Scalable: { std::vector<LRUCacheKey> keys; if (m_kind == CacheKind::Lru) { m_lruCache->snapshotKeys(keys); } else { m_scalableCache->snapshotKeys(keys); } for (auto& key: keys) { folly::writeFull(file.fd(), key.data(), key.size()); folly::writeFull(file.fd(), "\n", 1); } } break; } }
void PCRECache::dump(folly::File& file) { switch (m_kind) { case CacheKind::Static: for (auto& it : *m_staticCache) { folly::writeFull(file.fd(), it.first->data(), it.first->size()); folly::writeFull(file.fd(), "\n", 1); } break; case CacheKind::Lru: case CacheKind::Scalable: { std::vector<LRUCacheKey> keys; if (m_kind == CacheKind::Lru) { m_lruCache->snapshotKeys(keys); } else { m_scalableCache->snapshotKeys(keys); } for (auto& key: keys) { folly::writeFull(file.fd(), key.data(), key.size()); folly::writeFull(file.fd(), "\n", 1); } } break; } }
1,517
0
static inline bool migration_bitmap_test_and_reset_dirty(MemoryRegion *mr, ram_addr_t offset) { bool ret; int nr = (mr->ram_addr + offset) >> TARGET_PAGE_BITS; ret = test_and_clear_bit(nr, migration_bitmap); if (ret) { migration_dirty_pages--; } return ret; }
static inline bool migration_bitmap_test_and_reset_dirty(MemoryRegion *mr, ram_addr_t offset) { bool ret; int nr = (mr->ram_addr + offset) >> TARGET_PAGE_BITS; ret = test_and_clear_bit(nr, migration_bitmap); if (ret) { migration_dirty_pages--; } return ret; }
1,519
0
static void cirrus_vga_class_init ( ObjectClass * klass , void * data ) { DeviceClass * dc = DEVICE_CLASS ( klass ) ; PCIDeviceClass * k = PCI_DEVICE_CLASS ( klass ) ; k -> realize = pci_cirrus_vga_realize ; k -> romfile = VGABIOS_CIRRUS_FILENAME ; k -> vendor_id = PCI_VENDOR_ID_CIRRUS ; k -> device_id = CIRRUS_ID_CLGD5446 ; k -> class_id = PCI_CLASS_DISPLAY_VGA ; set_bit ( DEVICE_CATEGORY_DISPLAY , dc -> categories ) ; dc -> desc = "Cirrus CLGD 54xx VGA" ; dc -> vmsd = & vmstate_pci_cirrus_vga ; dc -> props = pci_vga_cirrus_properties ; dc -> hotpluggable = false ; }
static void cirrus_vga_class_init ( ObjectClass * klass , void * data ) { DeviceClass * dc = DEVICE_CLASS ( klass ) ; PCIDeviceClass * k = PCI_DEVICE_CLASS ( klass ) ; k -> realize = pci_cirrus_vga_realize ; k -> romfile = VGABIOS_CIRRUS_FILENAME ; k -> vendor_id = PCI_VENDOR_ID_CIRRUS ; k -> device_id = CIRRUS_ID_CLGD5446 ; k -> class_id = PCI_CLASS_DISPLAY_VGA ; set_bit ( DEVICE_CATEGORY_DISPLAY , dc -> categories ) ; dc -> desc = "Cirrus CLGD 54xx VGA" ; dc -> vmsd = & vmstate_pci_cirrus_vga ; dc -> props = pci_vga_cirrus_properties ; dc -> hotpluggable = false ; }
1,520
1
static int tc_fill_qdisc(struct sk_buff *skb, struct Qdisc *q, u32 clid, u32 pid, u32 seq, u16 flags, int event) { struct tcmsg *tcm; struct nlmsghdr *nlh; unsigned char *b = skb->tail; struct gnet_dump d; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*tcm), flags); tcm = NLMSG_DATA(nlh); tcm->tcm_family = AF_UNSPEC; tcm->tcm_ifindex = q->dev->ifindex; tcm->tcm_parent = clid; tcm->tcm_handle = q->handle; tcm->tcm_info = atomic_read(&q->refcnt); RTA_PUT(skb, TCA_KIND, IFNAMSIZ, q->ops->id); if (q->ops->dump && q->ops->dump(q, skb) < 0) goto rtattr_failure; q->qstats.qlen = q->q.qlen; if (gnet_stats_start_copy_compat(skb, TCA_STATS2, TCA_STATS, TCA_XSTATS, q->stats_lock, &d) < 0) goto rtattr_failure; if (q->ops->dump_stats && q->ops->dump_stats(q, &d) < 0) goto rtattr_failure; if (gnet_stats_copy_basic(&d, &q->bstats) < 0 || #ifdef CONFIG_NET_ESTIMATOR gnet_stats_copy_rate_est(&d, &q->rate_est) < 0 || #endif gnet_stats_copy_queue(&d, &q->qstats) < 0) goto rtattr_failure; if (gnet_stats_finish_copy(&d) < 0) goto rtattr_failure; nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: rtattr_failure: skb_trim(skb, b - skb->data); return -1; }
static int tc_fill_qdisc(struct sk_buff *skb, struct Qdisc *q, u32 clid, u32 pid, u32 seq, u16 flags, int event) { struct tcmsg *tcm; struct nlmsghdr *nlh; unsigned char *b = skb->tail; struct gnet_dump d; nlh = NLMSG_NEW(skb, pid, seq, event, sizeof(*tcm), flags); tcm = NLMSG_DATA(nlh); tcm->tcm_family = AF_UNSPEC; tcm->tcm_ifindex = q->dev->ifindex; tcm->tcm_parent = clid; tcm->tcm_handle = q->handle; tcm->tcm_info = atomic_read(&q->refcnt); RTA_PUT(skb, TCA_KIND, IFNAMSIZ, q->ops->id); if (q->ops->dump && q->ops->dump(q, skb) < 0) goto rtattr_failure; q->qstats.qlen = q->q.qlen; if (gnet_stats_start_copy_compat(skb, TCA_STATS2, TCA_STATS, TCA_XSTATS, q->stats_lock, &d) < 0) goto rtattr_failure; if (q->ops->dump_stats && q->ops->dump_stats(q, &d) < 0) goto rtattr_failure; if (gnet_stats_copy_basic(&d, &q->bstats) < 0 || #ifdef CONFIG_NET_ESTIMATOR gnet_stats_copy_rate_est(&d, &q->rate_est) < 0 || #endif gnet_stats_copy_queue(&d, &q->qstats) < 0) goto rtattr_failure; if (gnet_stats_finish_copy(&d) < 0) goto rtattr_failure; nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: rtattr_failure: skb_trim(skb, b - skb->data); return -1; }
1,523
0
PHP_FUNCTION ( uwsgi_cache_exists ) { char * key = NULL ; int keylen = 0 ; char * cache = NULL ; int cachelen = 0 ; if ( zend_parse_parameters ( ZEND_NUM_ARGS ( ) TSRMLS_CC , "s|s" , & key , & keylen , & cache , & cachelen ) == FAILURE ) { RETURN_NULL ( ) ; } if ( uwsgi_cache_magic_exists ( key , keylen , cache ) ) { RETURN_TRUE ; } RETURN_NULL ( ) ; }
PHP_FUNCTION ( uwsgi_cache_exists ) { char * key = NULL ; int keylen = 0 ; char * cache = NULL ; int cachelen = 0 ; if ( zend_parse_parameters ( ZEND_NUM_ARGS ( ) TSRMLS_CC , "s|s" , & key , & keylen , & cache , & cachelen ) == FAILURE ) { RETURN_NULL ( ) ; } if ( uwsgi_cache_magic_exists ( key , keylen , cache ) ) { RETURN_TRUE ; } RETURN_NULL ( ) ; }
1,524
1
void pcre_dump_cache(const std::string& filename) { s_pcreCache.dump(filename); }
void pcre_dump_cache(const std::string& filename) { s_pcreCache.dump(filename); }
1,525
1
static int neightbl_fill_param_info(struct neigh_table *tbl, struct neigh_parms *parms, struct sk_buff *skb, struct netlink_callback *cb) { struct ndtmsg *ndtmsg; struct nlmsghdr *nlh; nlh = NLMSG_NEW_ANSWER(skb, cb, RTM_NEWNEIGHTBL, sizeof(struct ndtmsg), NLM_F_MULTI); ndtmsg = NLMSG_DATA(nlh); read_lock_bh(&tbl->lock); ndtmsg->ndtm_family = tbl->family; RTA_PUT_STRING(skb, NDTA_NAME, tbl->id); if (neightbl_fill_parms(skb, parms) < 0) goto rtattr_failure; read_unlock_bh(&tbl->lock); return NLMSG_END(skb, nlh); rtattr_failure: read_unlock_bh(&tbl->lock); return NLMSG_CANCEL(skb, nlh); nlmsg_failure: return -1; }
static int neightbl_fill_param_info(struct neigh_table *tbl, struct neigh_parms *parms, struct sk_buff *skb, struct netlink_callback *cb) { struct ndtmsg *ndtmsg; struct nlmsghdr *nlh; nlh = NLMSG_NEW_ANSWER(skb, cb, RTM_NEWNEIGHTBL, sizeof(struct ndtmsg), NLM_F_MULTI); ndtmsg = NLMSG_DATA(nlh); read_lock_bh(&tbl->lock); ndtmsg->ndtm_family = tbl->family; RTA_PUT_STRING(skb, NDTA_NAME, tbl->id); if (neightbl_fill_parms(skb, parms) < 0) goto rtattr_failure; read_unlock_bh(&tbl->lock); return NLMSG_END(skb, nlh); rtattr_failure: read_unlock_bh(&tbl->lock); return NLMSG_CANCEL(skb, nlh); nlmsg_failure: return -1; }
1,526
0
void pcre_dump_cache(folly::File& file) { s_pcreCache.dump(file); }
void pcre_dump_cache(folly::File& file) { s_pcreCache.dump(file); }
1,527
0
static int qcow_set_key(BlockDriverState *bs, const char *key) { BDRVQcowState *s = bs->opaque; uint8_t keybuf[16]; int len, i; Error *err; memset(keybuf, 0, 16); len = strlen(key); if (len > 16) len = 16; /* XXX: we could compress the chars to 7 bits to increase entropy */ for(i = 0;i < len;i++) { keybuf[i] = key[i]; } assert(bs->encrypted); qcrypto_cipher_free(s->cipher); s->cipher = qcrypto_cipher_new( QCRYPTO_CIPHER_ALG_AES_128, QCRYPTO_CIPHER_MODE_CBC, keybuf, G_N_ELEMENTS(keybuf), &err); if (!s->cipher) { /* XXX would be nice if errors in this method could * be properly propagate to the caller. Would need * the bdrv_set_key() API signature to be fixed. */ error_free(err); return -1; } return 0; }
static int qcow_set_key(BlockDriverState *bs, const char *key) { BDRVQcowState *s = bs->opaque; uint8_t keybuf[16]; int len, i; Error *err; memset(keybuf, 0, 16); len = strlen(key); if (len > 16) len = 16; for(i = 0;i < len;i++) { keybuf[i] = key[i]; } assert(bs->encrypted); qcrypto_cipher_free(s->cipher); s->cipher = qcrypto_cipher_new( QCRYPTO_CIPHER_ALG_AES_128, QCRYPTO_CIPHER_MODE_CBC, keybuf, G_N_ELEMENTS(keybuf), &err); if (!s->cipher) { error_free(err); return -1; } return 0; }
1,528
0
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 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); }
1,529
0
void proto_register_amf ( void ) { static hf_register_info hf [ ] = { { & hf_amf_version , { "AMF version" , "amf.version" , FT_UINT16 , BASE_DEC , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_header_count , { "Header count" , "amf.header_count" , FT_UINT16 , BASE_DEC , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_header_name , { "Name" , "amf.header.name" , FT_UINT_STRING , BASE_NONE , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_header_must_understand , { "Must understand" , "amf.header.must_understand" , FT_BOOLEAN , BASE_NONE , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_header_length , { "Length" , "amf.header.length" , FT_UINT32 , BASE_DEC , NULL , 0x0 , NULL , HFILL } } , # if 0 { & hf_amf_header_value_type , { "Value type" , "amf.header.value_type" , FT_UINT32 , BASE_HEX , VALS ( rtmpt_type_vals ) , 0x0 , NULL , HFILL } } , # endif { & hf_amf_message_count , { "Message count" , "amf.message_count" , FT_UINT16 , BASE_DEC , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_message_target_uri , { "Target URI" , "amf.message.target_uri" , FT_UINT_STRING , BASE_NONE , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_message_response_uri , { "Response URI" , "amf.message.response_uri" , FT_UINT_STRING , BASE_NONE , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_message_length , { "Length" , "amf.message.length" , FT_UINT32 , BASE_DEC , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_amf0_type , { "AMF0 type" , "amf.amf0_type" , FT_UINT8 , BASE_HEX , VALS ( amf0_type_vals ) , 0x0 , NULL , HFILL } } , { & hf_amf_amf3_type , { "AMF3 type" , "amf.amf3_type" , FT_UINT8 , BASE_HEX , VALS ( amf3_type_vals ) , 0x0 , NULL , HFILL } } , { & hf_amf_number , { "Number" , "amf.number" , FT_DOUBLE , BASE_NONE , NULL , 0x0 , "AMF number" , HFILL } } , { & hf_amf_integer , { "Integer" , "amf.integer" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "RTMPT AMF3 integer" , HFILL } } , { & hf_amf_boolean , { "Boolean" , "amf.boolean" , FT_BOOLEAN , BASE_NONE , NULL , 0x0 , "AMF boolean" , HFILL } } , { & hf_amf_stringlength , { "String length" , "amf.stringlength" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF string length" , HFILL } } , { & hf_amf_string , { "String" , "amf.string" , FT_STRING , BASE_NONE , NULL , 0x0 , "AMF string" , HFILL } } , { & hf_amf_string_reference , { "String reference" , "amf.string_reference" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "RTMPT AMF3 string reference" , HFILL } } , { & hf_amf_object_reference , { "Object reference" , "amf.object_reference" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF object reference" , HFILL } } , { & hf_amf_date , { "Date" , "amf.date" , FT_ABSOLUTE_TIME , ABSOLUTE_TIME_LOCAL , NULL , 0x0 , "AMF date" , HFILL } } , # if 0 { & hf_amf_longstringlength , { "String length" , "amf.longstringlength" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF long string length" , HFILL } } , # endif { & hf_amf_longstring , { "Long string" , "amf.longstring" , FT_STRING , BASE_NONE , NULL , 0x0 , "AMF long string" , HFILL } } , { & hf_amf_xml_doc , { "XML document" , "amf.xml_doc" , FT_STRING , BASE_NONE , NULL , 0x0 , "AMF XML document" , HFILL } } , { & hf_amf_xmllength , { "XML text length" , "amf.xmllength" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF E4X XML length" , HFILL } } , { & hf_amf_xml , { "XML" , "amf.xml" , FT_STRING , BASE_NONE , NULL , 0x0 , "AMF E4X XML" , HFILL } } , { & hf_amf_int64 , { "Int64" , "amf.int64" , FT_INT64 , BASE_DEC , NULL , 0x0 , "AMF int64" , HFILL } } , { & hf_amf_bytearraylength , { "ByteArray length" , "amf.bytearraylength" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "RTMPT AMF3 ByteArray length" , HFILL } } , { & hf_amf_bytearray , { "ByteArray" , "amf.bytearray" , FT_BYTES , BASE_NONE , NULL , 0x0 , "RTMPT AMF3 ByteArray" , HFILL } } , { & hf_amf_object , { "Object" , "amf.object" , FT_NONE , BASE_NONE , NULL , 0x0 , "AMF object" , HFILL } } , { & hf_amf_traitcount , { "Trait count" , "amf.traitcount" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF count of traits for an object" , HFILL } } , { & hf_amf_classnamelength , { "Class name length" , "amf.classnamelength" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF class name length" , HFILL } } , { & hf_amf_classname , { "Class name" , "amf.classname" , FT_STRING , BASE_NONE , NULL , 0x0 , "AMF class name" , HFILL } } , { & hf_amf_membernamelength , { "Member name length" , "amf.membernamelength" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF member name length" , HFILL } } , { & hf_amf_membername , { "Member name" , "amf.membername" , FT_STRING , BASE_NONE , NULL , 0x0 , "AMF member name" , HFILL } } , { & hf_amf_trait_reference , { "Trait reference" , "amf.trait_reference" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF trait reference" , HFILL } } , { & hf_amf_ecmaarray , { "ECMA array" , "amf.ecmaarray" , FT_NONE , BASE_NONE , NULL , 0x0 , "AMF ECMA array" , HFILL } } , { & hf_amf_strictarray , { "Strict array" , "amf.strictarray" , FT_NONE , BASE_NONE , NULL , 0x0 , "AMF strict array" , HFILL } } , { & hf_amf_array , { "Array" , "amf.array" , FT_NONE , BASE_NONE , NULL , 0x0 , "RTMPT AMF3 array" , HFILL } } , { & hf_amf_arraylength , { "Array length" , "amf.arraylength" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF array length" , HFILL } } , { & hf_amf_arraydenselength , { "Length of dense portion" , "amf.arraydenselength" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF length of dense portion of array" , HFILL } } , { & hf_amf_end_of_object_marker , { "End Of Object Marker" , "amf.end_of_object_marker" , FT_NONE , BASE_NONE , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_end_of_associative_part , { "End of associative part" , "amf.end_of_associative_part" , FT_NONE , BASE_NONE , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_end_of_dynamic_members , { "End Of dynamic members" , "amf.end_of_dynamic_members" , FT_NONE , BASE_NONE , NULL , 0x0 , NULL , HFILL } } , } ; static gint * ett [ ] = { & ett_amf , & ett_amf_headers , & ett_amf_messages , & ett_amf_value , & ett_amf_property , & ett_amf_string , & ett_amf_array_element , & ett_amf_traits , & ett_amf_trait_member , } ; proto_amf = proto_register_protocol ( "Action Message Format" , "AMF" , "amf" ) ; proto_register_field_array ( proto_amf , hf , array_length ( hf ) ) ; proto_register_subtree_array ( ett , array_length ( ett ) ) ; }
void proto_register_amf ( void ) { static hf_register_info hf [ ] = { { & hf_amf_version , { "AMF version" , "amf.version" , FT_UINT16 , BASE_DEC , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_header_count , { "Header count" , "amf.header_count" , FT_UINT16 , BASE_DEC , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_header_name , { "Name" , "amf.header.name" , FT_UINT_STRING , BASE_NONE , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_header_must_understand , { "Must understand" , "amf.header.must_understand" , FT_BOOLEAN , BASE_NONE , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_header_length , { "Length" , "amf.header.length" , FT_UINT32 , BASE_DEC , NULL , 0x0 , NULL , HFILL } } , # if 0 { & hf_amf_header_value_type , { "Value type" , "amf.header.value_type" , FT_UINT32 , BASE_HEX , VALS ( rtmpt_type_vals ) , 0x0 , NULL , HFILL } } , # endif { & hf_amf_message_count , { "Message count" , "amf.message_count" , FT_UINT16 , BASE_DEC , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_message_target_uri , { "Target URI" , "amf.message.target_uri" , FT_UINT_STRING , BASE_NONE , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_message_response_uri , { "Response URI" , "amf.message.response_uri" , FT_UINT_STRING , BASE_NONE , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_message_length , { "Length" , "amf.message.length" , FT_UINT32 , BASE_DEC , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_amf0_type , { "AMF0 type" , "amf.amf0_type" , FT_UINT8 , BASE_HEX , VALS ( amf0_type_vals ) , 0x0 , NULL , HFILL } } , { & hf_amf_amf3_type , { "AMF3 type" , "amf.amf3_type" , FT_UINT8 , BASE_HEX , VALS ( amf3_type_vals ) , 0x0 , NULL , HFILL } } , { & hf_amf_number , { "Number" , "amf.number" , FT_DOUBLE , BASE_NONE , NULL , 0x0 , "AMF number" , HFILL } } , { & hf_amf_integer , { "Integer" , "amf.integer" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "RTMPT AMF3 integer" , HFILL } } , { & hf_amf_boolean , { "Boolean" , "amf.boolean" , FT_BOOLEAN , BASE_NONE , NULL , 0x0 , "AMF boolean" , HFILL } } , { & hf_amf_stringlength , { "String length" , "amf.stringlength" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF string length" , HFILL } } , { & hf_amf_string , { "String" , "amf.string" , FT_STRING , BASE_NONE , NULL , 0x0 , "AMF string" , HFILL } } , { & hf_amf_string_reference , { "String reference" , "amf.string_reference" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "RTMPT AMF3 string reference" , HFILL } } , { & hf_amf_object_reference , { "Object reference" , "amf.object_reference" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF object reference" , HFILL } } , { & hf_amf_date , { "Date" , "amf.date" , FT_ABSOLUTE_TIME , ABSOLUTE_TIME_LOCAL , NULL , 0x0 , "AMF date" , HFILL } } , # if 0 { & hf_amf_longstringlength , { "String length" , "amf.longstringlength" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF long string length" , HFILL } } , # endif { & hf_amf_longstring , { "Long string" , "amf.longstring" , FT_STRING , BASE_NONE , NULL , 0x0 , "AMF long string" , HFILL } } , { & hf_amf_xml_doc , { "XML document" , "amf.xml_doc" , FT_STRING , BASE_NONE , NULL , 0x0 , "AMF XML document" , HFILL } } , { & hf_amf_xmllength , { "XML text length" , "amf.xmllength" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF E4X XML length" , HFILL } } , { & hf_amf_xml , { "XML" , "amf.xml" , FT_STRING , BASE_NONE , NULL , 0x0 , "AMF E4X XML" , HFILL } } , { & hf_amf_int64 , { "Int64" , "amf.int64" , FT_INT64 , BASE_DEC , NULL , 0x0 , "AMF int64" , HFILL } } , { & hf_amf_bytearraylength , { "ByteArray length" , "amf.bytearraylength" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "RTMPT AMF3 ByteArray length" , HFILL } } , { & hf_amf_bytearray , { "ByteArray" , "amf.bytearray" , FT_BYTES , BASE_NONE , NULL , 0x0 , "RTMPT AMF3 ByteArray" , HFILL } } , { & hf_amf_object , { "Object" , "amf.object" , FT_NONE , BASE_NONE , NULL , 0x0 , "AMF object" , HFILL } } , { & hf_amf_traitcount , { "Trait count" , "amf.traitcount" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF count of traits for an object" , HFILL } } , { & hf_amf_classnamelength , { "Class name length" , "amf.classnamelength" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF class name length" , HFILL } } , { & hf_amf_classname , { "Class name" , "amf.classname" , FT_STRING , BASE_NONE , NULL , 0x0 , "AMF class name" , HFILL } } , { & hf_amf_membernamelength , { "Member name length" , "amf.membernamelength" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF member name length" , HFILL } } , { & hf_amf_membername , { "Member name" , "amf.membername" , FT_STRING , BASE_NONE , NULL , 0x0 , "AMF member name" , HFILL } } , { & hf_amf_trait_reference , { "Trait reference" , "amf.trait_reference" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF trait reference" , HFILL } } , { & hf_amf_ecmaarray , { "ECMA array" , "amf.ecmaarray" , FT_NONE , BASE_NONE , NULL , 0x0 , "AMF ECMA array" , HFILL } } , { & hf_amf_strictarray , { "Strict array" , "amf.strictarray" , FT_NONE , BASE_NONE , NULL , 0x0 , "AMF strict array" , HFILL } } , { & hf_amf_array , { "Array" , "amf.array" , FT_NONE , BASE_NONE , NULL , 0x0 , "RTMPT AMF3 array" , HFILL } } , { & hf_amf_arraylength , { "Array length" , "amf.arraylength" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF array length" , HFILL } } , { & hf_amf_arraydenselength , { "Length of dense portion" , "amf.arraydenselength" , FT_UINT32 , BASE_DEC , NULL , 0x0 , "AMF length of dense portion of array" , HFILL } } , { & hf_amf_end_of_object_marker , { "End Of Object Marker" , "amf.end_of_object_marker" , FT_NONE , BASE_NONE , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_end_of_associative_part , { "End of associative part" , "amf.end_of_associative_part" , FT_NONE , BASE_NONE , NULL , 0x0 , NULL , HFILL } } , { & hf_amf_end_of_dynamic_members , { "End Of dynamic members" , "amf.end_of_dynamic_members" , FT_NONE , BASE_NONE , NULL , 0x0 , NULL , HFILL } } , } ; static gint * ett [ ] = { & ett_amf , & ett_amf_headers , & ett_amf_messages , & ett_amf_value , & ett_amf_property , & ett_amf_string , & ett_amf_array_element , & ett_amf_traits , & ett_amf_trait_member , } ; proto_amf = proto_register_protocol ( "Action Message Format" , "AMF" , "amf" ) ; proto_register_field_array ( proto_amf , hf , array_length ( hf ) ) ; proto_register_subtree_array ( ett , array_length ( ett ) ) ; }
1,530
0
int vhost_dev_init(struct vhost_dev *hdev, int devfd, const char *devpath, bool force) { uint64_t features; int r; if (devfd >= 0) { hdev->control = devfd; } else { hdev->control = open(devpath, O_RDWR); if (hdev->control < 0) { return -errno; } } r = ioctl(hdev->control, VHOST_SET_OWNER, NULL); if (r < 0) { goto fail; } r = ioctl(hdev->control, VHOST_GET_FEATURES, &features); if (r < 0) { goto fail; } hdev->features = features; hdev->memory_listener = (MemoryListener) { .begin = vhost_begin, .commit = vhost_commit, .region_add = vhost_region_add, .region_del = vhost_region_del, .region_nop = vhost_region_nop, .log_start = vhost_log_start, .log_stop = vhost_log_stop, .log_sync = vhost_log_sync, .log_global_start = vhost_log_global_start, .log_global_stop = vhost_log_global_stop, .eventfd_add = vhost_eventfd_add, .eventfd_del = vhost_eventfd_del, .priority = 10 }; hdev->mem = g_malloc0(offsetof(struct vhost_memory, regions)); hdev->n_mem_sections = 0; hdev->mem_sections = NULL; hdev->log = NULL; hdev->log_size = 0; hdev->log_enabled = false; hdev->started = false; memory_listener_register(&hdev->memory_listener, NULL); hdev->force = force; return 0; fail: r = -errno; close(hdev->control); return r; }
int vhost_dev_init(struct vhost_dev *hdev, int devfd, const char *devpath, bool force) { uint64_t features; int r; if (devfd >= 0) { hdev->control = devfd; } else { hdev->control = open(devpath, O_RDWR); if (hdev->control < 0) { return -errno; } } r = ioctl(hdev->control, VHOST_SET_OWNER, NULL); if (r < 0) { goto fail; } r = ioctl(hdev->control, VHOST_GET_FEATURES, &features); if (r < 0) { goto fail; } hdev->features = features; hdev->memory_listener = (MemoryListener) { .begin = vhost_begin, .commit = vhost_commit, .region_add = vhost_region_add, .region_del = vhost_region_del, .region_nop = vhost_region_nop, .log_start = vhost_log_start, .log_stop = vhost_log_stop, .log_sync = vhost_log_sync, .log_global_start = vhost_log_global_start, .log_global_stop = vhost_log_global_stop, .eventfd_add = vhost_eventfd_add, .eventfd_del = vhost_eventfd_del, .priority = 10 }; hdev->mem = g_malloc0(offsetof(struct vhost_memory, regions)); hdev->n_mem_sections = 0; hdev->mem_sections = NULL; hdev->log = NULL; hdev->log_size = 0; hdev->log_enabled = false; hdev->started = false; memory_listener_register(&hdev->memory_listener, NULL); hdev->force = force; return 0; fail: r = -errno; close(hdev->control); return r; }
1,532
1
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; vma_stop(priv, vma); if (priv->task) put_task_struct(priv->task); }
1,533
0
void RuntimeOption::Load( IniSetting::Map& ini, Hdf& config, const std::vector<std::string>& iniClis /* = std::vector<std::string>() */, const std::vector<std::string>& hdfClis /* = std::vector<std::string>() */, std::vector<std::string>* messages /* = nullptr */, std::string cmd /* = "" */) { ARRPROV_USE_RUNTIME_LOCATION_FORCE(); // Intialize the memory manager here because various settings and // initializations that we do here need it tl_heap.getCheck(); // Get the ini (-d) and hdf (-v) strings, which may override some // of options that were set from config files. We also do these // now so we can override Tier.*.[machine | tier | cpu] on the // command line, along with any fields within a Tier (e.g., // CoreFileSize) for (auto& istr : iniClis) { Config::ParseIniString(istr, ini); } for (auto& hstr : hdfClis) { Config::ParseHdfString(hstr, config); } // See if there are any Tier-based overrides auto m = getTierOverwrites(ini, config); if (messages) *messages = std::move(m); // RelativeConfigs can be set by commandline flags and tier overwrites, they // may also contain tier overwrites. They are, however, only included once, so // relative configs may not specify other relative configs which must to be // loaded. If RelativeConfigs is modified while loading configs an error is // raised, but we defer doing so until the logger is initialized below. If a // relative config cannot be found it is silently skipped (this is to allow // configs to be conditionally applied to scripts based on their location). By // reading the "hhvm.relative_configs" ini setting at runtime it is possible // to determine which configs were actually loaded. std::string relConfigsError; Config::Bind(s_RelativeConfigs, ini, config, "RelativeConfigs"); if (!cmd.empty() && !s_RelativeConfigs.empty()) { String strcmd(cmd, CopyString); Process::InitProcessStatics(); auto const currentDir = Process::CurrentWorkingDirectory.data(); std::vector<std::string> newConfigs; auto const original = s_RelativeConfigs; for (auto& str : original) { if (str.empty()) continue; std::string fullpath; auto const found = FileUtil::runRelative( str, strcmd, currentDir, [&] (const String& f) { if (access(f.data(), R_OK) == 0) { fullpath = f.toCppString(); FTRACE_MOD(Trace::watchman_autoload, 3, "Parsing {}\n", fullpath); Config::ParseConfigFile(fullpath, ini, config); return true; } return false; } ); if (found) newConfigs.emplace_back(std::move(fullpath)); } if (!newConfigs.empty()) { auto m2 = getTierOverwrites(ini, config); if (messages) *messages = std::move(m2); if (s_RelativeConfigs != original) { relConfigsError = folly::sformat( "RelativeConfigs node was modified while loading configs from [{}] " "to [{}]", folly::join(", ", original), folly::join(", ", s_RelativeConfigs) ); } } s_RelativeConfigs.swap(newConfigs); } else { s_RelativeConfigs.clear(); } // Then get the ini and hdf cli strings again, in case the tier overwrites // overrode any non-tier based command line option we set. The tier-based // command line overwrites will already have been set in the call above. // This extra call is for the other command line options that may have been // overridden by a tier, but shouldn't have been. for (auto& istr : iniClis) { Config::ParseIniString(istr, ini); } for (auto& hstr : hdfClis) { Config::ParseHdfString(hstr, config); } Config::Bind(PidFile, ini, config, "PidFile", "www.pid"); Config::Bind(DeploymentId, ini, config, "DeploymentId"); { static std::string deploymentIdOverride; Config::Bind(deploymentIdOverride, ini, config, "DeploymentIdOverride"); if (!deploymentIdOverride.empty()) { RuntimeOption::DeploymentId = deploymentIdOverride; } } { // Config ID Config::Bind(ConfigId, ini, config, "ConfigId", 0); auto configIdCounter = ServiceData::createCounter("vm.config.id"); configIdCounter->setValue(ConfigId); } { // Logging auto setLogLevel = [](const std::string& value) { // ini parsing treats "None" as "" if (value == "None" || value == "") { Logger::LogLevel = Logger::LogNone; } else if (value == "Error") { Logger::LogLevel = Logger::LogError; } else if (value == "Warning") { Logger::LogLevel = Logger::LogWarning; } else if (value == "Info") { Logger::LogLevel = Logger::LogInfo; } else if (value == "Verbose") { Logger::LogLevel = Logger::LogVerbose; } else { return false; } return true; }; auto str = Config::GetString(ini, config, "Log.Level"); if (!str.empty()) { setLogLevel(str); } IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_SYSTEM, "hhvm.log.level", IniSetting::SetAndGet<std::string>( setLogLevel, []() { switch (Logger::LogLevel) { case Logger::LogNone: return "None"; case Logger::LogError: return "Error"; case Logger::LogWarning: return "Warning"; case Logger::LogInfo: return "Info"; case Logger::LogVerbose: return "Verbose"; } return ""; } )); Config::Bind(Logger::UseLogFile, ini, config, "Log.UseLogFile", true); Config::Bind(LogFile, ini, config, "Log.File"); Config::Bind(LogFileSymLink, ini, config, "Log.SymLink"); Config::Bind(LogFilePeriodMultiplier, ini, config, "Log.PeriodMultiplier", 0); if (Logger::UseLogFile && RuntimeOption::ServerExecutionMode()) { RuntimeOption::ErrorLogs[Logger::DEFAULT] = ErrorLogFileData(LogFile, LogFileSymLink, LogFilePeriodMultiplier); } if (Config::GetBool(ini, config, "Log.AlwaysPrintStackTraces")) { Logger::SetTheLogger(Logger::DEFAULT, new ExtendedLogger()); ExtendedLogger::EnabledByDefault = true; } Config::Bind(Logger::LogHeader, ini, config, "Log.Header"); Config::Bind(Logger::LogNativeStackTrace, ini, config, "Log.NativeStackTrace", true); Config::Bind(Logger::UseSyslog, ini, config, "Log.UseSyslog", false); Config::Bind(Logger::UseRequestLog, ini, config, "Log.UseRequestLog", false); Config::Bind(Logger::AlwaysEscapeLog, ini, config, "Log.AlwaysEscapeLog", true); Config::Bind(Logger::UseCronolog, ini, config, "Log.UseCronolog", false); Config::Bind(Logger::MaxMessagesPerRequest, ini, config, "Log.MaxMessagesPerRequest", -1); Config::Bind(LogFileFlusher::DropCacheChunkSize, ini, config, "Log.DropCacheChunkSize", 1 << 20); Config::Bind(RuntimeOption::LogHeaderMangle, ini, config, "Log.HeaderMangle", 0); Config::Bind(AlwaysLogUnhandledExceptions, ini, config, "Log.AlwaysLogUnhandledExceptions", true); Config::Bind(NoSilencer, ini, config, "Log.NoSilencer"); Config::Bind(RuntimeErrorReportingLevel, ini, config, "Log.RuntimeErrorReportingLevel", static_cast<int>(ErrorMode::HPHP_ALL)); Config::Bind(ForceErrorReportingLevel, ini, config, "Log.ForceErrorReportingLevel", 0); Config::Bind(AccessLogDefaultFormat, ini, config, "Log.AccessLogDefaultFormat", "%h %l %u %t \"%r\" %>s %b"); auto parseLogs = [] (const Hdf &config, const IniSetting::Map& ini, const std::string &name, std::map<std::string, AccessLogFileData> &logs) { auto parse_logs_callback = [&] (const IniSetting::Map &ini_pl, const Hdf &hdf_pl, const std::string &ini_pl_key) { string logName = hdf_pl.exists() && !hdf_pl.isEmpty() ? hdf_pl.getName() : ini_pl_key; string fname = Config::GetString(ini_pl, hdf_pl, "File", "", false); if (!fname.empty()) { string symlink = Config::GetString(ini_pl, hdf_pl, "SymLink", "", false); string format = Config::GetString(ini_pl, hdf_pl, "Format", AccessLogDefaultFormat, false); auto periodMultiplier = Config::GetUInt16(ini_pl, hdf_pl, "PeriodMultiplier", 0, false); logs[logName] = AccessLogFileData(fname, symlink, format, periodMultiplier); } }; Config::Iterate(parse_logs_callback, ini, config, name); }; parseLogs(config, ini, "Log.Access", AccessLogs); RPCLogs = AccessLogs; parseLogs(config, ini, "Log.RPC", RPCLogs); Config::Bind(AdminLogFormat, ini, config, "Log.AdminLog.Format", "%h %t %s %U"); Config::Bind(AdminLogFile, ini, config, "Log.AdminLog.File"); Config::Bind(AdminLogSymLink, ini, config, "Log.AdminLog.SymLink"); } { // Error Handling Config::Bind(ErrorUpgradeLevel, ini, config, "ErrorHandling.UpgradeLevel", 0); Config::Bind(MaxSerializedStringSize, ini, config, "ErrorHandling.MaxSerializedStringSize", 64 * 1024 * 1024); Config::Bind(CallUserHandlerOnFatals, ini, config, "ErrorHandling.CallUserHandlerOnFatals", false); Config::Bind(ThrowExceptionOnBadMethodCall, ini, config, "ErrorHandling.ThrowExceptionOnBadMethodCall", true); Config::Bind(LogNativeStackOnOOM, ini, config, "ErrorHandling.LogNativeStackOnOOM", false); Config::Bind(NoInfiniteRecursionDetection, ini, config, "ErrorHandling.NoInfiniteRecursionDetection"); Config::Bind(NoticeFrequency, ini, config, "ErrorHandling.NoticeFrequency", 1); Config::Bind(WarningFrequency, ini, config, "ErrorHandling.WarningFrequency", 1); } // If we generated errors while loading RelativeConfigs report those now that // error reporting is initialized if (!relConfigsError.empty()) Logger::Error(relConfigsError); { if (Config::GetInt64(ini, config, "ResourceLimit.CoreFileSizeOverride")) { setResourceLimit(RLIMIT_CORE, ini, config, "ResourceLimit.CoreFileSizeOverride"); } else { setResourceLimit(RLIMIT_CORE, ini, config, "ResourceLimit.CoreFileSize"); } setResourceLimit(RLIMIT_NOFILE, ini, config, "ResourceLimit.MaxSocket"); setResourceLimit(RLIMIT_DATA, ini, config, "ResourceLimit.RSS"); // These don't have RuntimeOption::xxx bindings, but we still want to be // able to use ini_xxx functionality on them; so directly bind to a local // static via Config::Bind. static int64_t s_core_file_size_override, s_core_file_size, s_rss = 0; static int32_t s_max_socket = 0; Config::Bind(s_core_file_size_override, ini, config, "ResourceLimit.CoreFileSizeOverride", 0); Config::Bind(s_core_file_size, ini, config, "ResourceLimit.CoreFileSize", 0); Config::Bind(s_max_socket, ini, config, "ResourceLimit.MaxSocket", 0); Config::Bind(s_rss, ini, config, "ResourceLimit.RSS", 0); Config::Bind(SocketDefaultTimeout, ini, config, "ResourceLimit.SocketDefaultTimeout", 60); Config::Bind(MaxSQLRowCount, ini, config, "ResourceLimit.MaxSQLRowCount", 0); Config::Bind(SerializationSizeLimit, ini, config, "ResourceLimit.SerializationSizeLimit", StringData::MaxSize); Config::Bind(HeapSizeMB, ini, config, "ResourceLimit.HeapSizeMB", HeapSizeMB); Config::Bind(HeapResetCountBase, ini, config, "ResourceLimit.HeapResetCountBase", HeapResetCountBase); Config::Bind(HeapResetCountMultiple, ini, config, "ResourceLimit.HeapResetCountMultiple", HeapResetCountMultiple); Config::Bind(HeapLowWaterMark , ini, config, "ResourceLimit.HeapLowWaterMark", HeapLowWaterMark); Config::Bind(HeapHighWaterMark , ini, config, "ResourceLimit.HeapHighWaterMark",HeapHighWaterMark); } { // PHPisms Config::Bind(DisableCallUserFunc, ini, config, "Hack.Lang.Phpism.DisableCallUserFunc", DisableCallUserFunc); Config::Bind(DisableCallUserFuncArray, ini, config, "Hack.Lang.Phpism.DisableCallUserFuncArray", DisableCallUserFuncArray); Config::Bind(DisableAssert, ini, config, "Hack.Lang.Phpism.DisableAssert", DisableAssert); Config::Bind(DisableNontoplevelDeclarations, ini, config, "Hack.Lang.Phpism.DisableNontoplevelDeclarations", DisableNontoplevelDeclarations); Config::Bind(DisableStaticClosures, ini, config, "Hack.Lang.Phpism.DisableStaticClosures", DisableStaticClosures); Config::Bind(DisableConstant, ini, config, "Hack.Lang.Phpism.DisableConstant", DisableConstant); } { // Repo auto repoModeToStr = [](RepoMode mode) { switch (mode) { case RepoMode::Closed: return "--"; case RepoMode::ReadOnly: return "r-"; case RepoMode::ReadWrite: return "rw"; } always_assert(false); return ""; }; auto parseRepoMode = [&](const std::string& repoModeStr, const char* type, RepoMode defaultMode) { if (repoModeStr.empty()) { return defaultMode; } if (repoModeStr == "--") { return RepoMode::Closed; } if (repoModeStr == "r-") { return RepoMode::ReadOnly; } if (repoModeStr == "rw") { return RepoMode::ReadWrite; } Logger::Error("Bad config setting: Repo.%s.Mode=%s", type, repoModeStr.c_str()); return RepoMode::ReadWrite; }; // Local Repo static std::string repoLocalMode; Config::Bind(repoLocalMode, ini, config, "Repo.Local.Mode", repoModeToStr(RepoLocalMode)); RepoLocalMode = parseRepoMode(repoLocalMode, "Local", RepoMode::ReadOnly); // Repo.Local.Path Config::Bind(RepoLocalPath, ini, config, "Repo.Local.Path"); if (RepoLocalPath.empty()) { const char* HHVM_REPO_LOCAL_PATH = getenv("HHVM_REPO_LOCAL_PATH"); if (HHVM_REPO_LOCAL_PATH != nullptr) { RepoLocalPath = HHVM_REPO_LOCAL_PATH; } } // Central Repo static std::string repoCentralMode; Config::Bind(repoCentralMode, ini, config, "Repo.Central.Mode", repoModeToStr(RepoCentralMode)); RepoCentralMode = parseRepoMode(repoCentralMode, "Central", RepoMode::ReadWrite); // Repo.Central.Path Config::Bind(RepoCentralPath, ini, config, "Repo.Central.Path"); Config::Bind(RepoCentralFileMode, ini, config, "Repo.Central.FileMode"); Config::Bind(RepoCentralFileUser, ini, config, "Repo.Central.FileUser"); Config::Bind(RepoCentralFileGroup, ini, config, "Repo.Central.FileGroup"); Config::Bind(RepoAllowFallbackPath, ini, config, "Repo.AllowFallbackPath", RepoAllowFallbackPath); replacePlaceholders(RepoLocalPath); replacePlaceholders(RepoCentralPath); Config::Bind(RepoJournal, ini, config, "Repo.Journal", RepoJournal); Config::Bind(RepoCommit, ini, config, "Repo.Commit", RepoCommit); Config::Bind(RepoDebugInfo, ini, config, "Repo.DebugInfo", RepoDebugInfo); Config::Bind(RepoLitstrLazyLoad, ini, config, "Repo.LitstrLazyLoad", RepoLitstrLazyLoad); Config::Bind(RepoAuthoritative, ini, config, "Repo.Authoritative", RepoAuthoritative); Config::Bind(RepoLocalReadaheadRate, ini, config, "Repo.LocalReadaheadRate", 0); Config::Bind(RepoLocalReadaheadConcurrent, ini, config, "Repo.LocalReadaheadConcurrent", false); Config::Bind(RepoBusyTimeoutMS, ini, config, "Repo.BusyTimeoutMS", RepoBusyTimeoutMS); } if (use_jemalloc) { // HHProf Config::Bind(HHProfEnabled, ini, config, "HHProf.Enabled", false); Config::Bind(HHProfActive, ini, config, "HHProf.Active", false); Config::Bind(HHProfAccum, ini, config, "HHProf.Accum", false); Config::Bind(HHProfRequest, ini, config, "HHProf.Request", false); } { // Eval Config::Bind(EnableHipHopSyntax, ini, config, "Eval.EnableHipHopSyntax", EnableHipHopSyntax); Config::Bind(EnableShortTags, ini, config, "Eval.EnableShortTags", true); Config::Bind(EnableXHP, ini, config, "Eval.EnableXHP", EnableXHP); Config::Bind(TimeoutsUseWallTime, ini, config, "Eval.TimeoutsUseWallTime", true); Config::Bind(CheckFlushOnUserClose, ini, config, "Eval.CheckFlushOnUserClose", true); Config::Bind(EvalInitialNamedEntityTableSize, ini, config, "Eval.InitialNamedEntityTableSize", EvalInitialNamedEntityTableSize); Config::Bind(EvalInitialStaticStringTableSize, ini, config, "Eval.InitialStaticStringTableSize", EvalInitialStaticStringTableSize); static std::string jitSerdesMode; Config::Bind(jitSerdesMode, ini, config, "Eval.JitSerdesMode", "Off"); EvalJitSerdesMode = [&] { #define X(x) if (jitSerdesMode == #x) return JitSerdesMode::x X(Serialize); X(SerializeAndExit); X(Deserialize); X(DeserializeOrFail); X(DeserializeOrGenerate); X(DeserializeAndDelete); X(DeserializeAndExit); #undef X return JitSerdesMode::Off; }(); Config::Bind(EvalJitSerdesFile, ini, config, "Eval.JitSerdesFile", EvalJitSerdesFile); // DumpPreciseProfileData defaults to true only when we can possibly write // profile data to disk. It can be set to false to avoid the performance // penalty of only running the interpreter during retranslateAll. We will // assume that DumpPreciseProfileData implies (JitSerdesMode::Serialize || // JitSerdesMode::SerializeAndExit), to avoid checking too many flags in a // few places. The config file should never need to explicitly set // DumpPreciseProfileData to true. auto const couldDump = !EvalJitSerdesFile.empty() && (isJitSerializing() || (EvalJitSerdesMode == JitSerdesMode::DeserializeOrGenerate)); Config::Bind(DumpPreciseProfData, ini, config, "Eval.DumpPreciseProfData", couldDump); Config::Bind(ProfDataTTLHours, ini, config, "Eval.ProfDataTTLHours", ProfDataTTLHours); Config::Bind(ProfDataTag, ini, config, "Eval.ProfDataTag", ProfDataTag); Config::Bind(CheckSymLink, ini, config, "Eval.CheckSymLink", true); Config::Bind(TrustAutoloaderPath, ini, config, "Eval.TrustAutoloaderPath", false); #define F(type, name, defaultVal) \ Config::Bind(Eval ## name, ini, config, "Eval."#name, defaultVal); EVALFLAGS() #undef F if (EvalJitSerdesModeForceOff) EvalJitSerdesMode = JitSerdesMode::Off; if (!EvalEnableReusableTC) EvalReusableTCPadding = 0; if (numa_num_nodes <= 1) { EvalEnableNuma = false; } Config::Bind(ServerForkEnabled, ini, config, "Server.Forking.Enabled", ServerForkEnabled); Config::Bind(ServerForkLogging, ini, config, "Server.Forking.LogForkAttempts", ServerForkLogging); if (!ServerForkEnabled && ServerExecutionMode()) { // Only use hugetlb pages when we don't fork(). low_2m_pages(EvalMaxLowMemHugePages); high_2m_pages(EvalMaxHighArenaHugePages); } s_enable_static_arena = Config::GetBool(ini, config, "Eval.UseTLStaticArena", true); replacePlaceholders(EvalHackCompilerExtractPath); replacePlaceholders(EvalHackCompilerFallbackPath); replacePlaceholders(EvalEmbeddedDataExtractPath); replacePlaceholders(EvalEmbeddedDataFallbackPath); if (!jit::mcgen::retranslateAllEnabled()) { EvalJitWorkerThreads = 0; if (EvalJitSerdesMode != JitSerdesMode::Off) { if (ServerMode) { Logger::Warning("Eval.JitSerdesMode reset from " + jitSerdesMode + " to off, becasue JitRetranslateAll isn't enabled."); } EvalJitSerdesMode = JitSerdesMode::Off; } EvalJitSerdesFile.clear(); DumpPreciseProfData = false; } EvalJitPGOUseAddrCountedCheck &= addr_encodes_persistency; HardwareCounter::Init(EvalProfileHWEnable, url_decode(EvalProfileHWEvents.data(), EvalProfileHWEvents.size()).toCppString(), false, EvalProfileHWExcludeKernel, EvalProfileHWFastReads, EvalProfileHWExportInterval); Config::Bind(EnableIntrinsicsExtension, ini, config, "Eval.EnableIntrinsicsExtension", EnableIntrinsicsExtension); Config::Bind(RecordCodeCoverage, ini, config, "Eval.RecordCodeCoverage"); if (EvalJit && RecordCodeCoverage) { throw std::runtime_error("Code coverage is not supported with " "Eval.Jit=true"); } Config::Bind(DisableSmallAllocator, ini, config, "Eval.DisableSmallAllocator", DisableSmallAllocator); SetArenaSlabAllocBypass(DisableSmallAllocator); EvalSlabAllocAlign = folly::nextPowTwo(EvalSlabAllocAlign); EvalSlabAllocAlign = std::min(EvalSlabAllocAlign, decltype(EvalSlabAllocAlign){4096}); if (RecordCodeCoverage) CheckSymLink = true; Config::Bind(CodeCoverageOutputFile, ini, config, "Eval.CodeCoverageOutputFile"); // NB: after we know the value of RepoAuthoritative. Config::Bind(EnableArgsInBacktraces, ini, config, "Eval.EnableArgsInBacktraces", !RepoAuthoritative); Config::Bind(EvalAuthoritativeMode, ini, config, "Eval.AuthoritativeMode", false); Config::Bind(CheckCLIClientCommands, ini, config, "Eval.CheckCLIClientCommands", 1); if (RepoAuthoritative) { EvalAuthoritativeMode = true; } { // Debugger (part of Eval) Config::Bind(EnableHphpdDebugger, ini, config, "Eval.Debugger.EnableDebugger"); Config::Bind(EnableDebuggerColor, ini, config, "Eval.Debugger.EnableDebuggerColor", true); Config::Bind(EnableDebuggerPrompt, ini, config, "Eval.Debugger.EnableDebuggerPrompt", true); Config::Bind(EnableDebuggerServer, ini, config, "Eval.Debugger.EnableDebuggerServer"); Config::Bind(EnableDebuggerUsageLog, ini, config, "Eval.Debugger.EnableDebuggerUsageLog"); Config::Bind(DebuggerServerIP, ini, config, "Eval.Debugger.IP"); Config::Bind(DebuggerServerPort, ini, config, "Eval.Debugger.Port", 8089); Config::Bind(DebuggerDisableIPv6, ini, config, "Eval.Debugger.DisableIPv6", false); Config::Bind(DebuggerDefaultSandboxPath, ini, config, "Eval.Debugger.DefaultSandboxPath"); Config::Bind(DebuggerStartupDocument, ini, config, "Eval.Debugger.StartupDocument"); Config::Bind(DebuggerSignalTimeout, ini, config, "Eval.Debugger.SignalTimeout", 1); Config::Bind(DebuggerDefaultRpcPort, ini, config, "Eval.Debugger.RPC.DefaultPort", 8083); DebuggerDefaultRpcAuth = Config::GetString(ini, config, "Eval.Debugger.RPC.DefaultAuth"); Config::Bind(DebuggerRpcHostDomain, ini, config, "Eval.Debugger.RPC.HostDomain"); Config::Bind(DebuggerDefaultRpcTimeout, ini, config, "Eval.Debugger.RPC.DefaultTimeout", 30); Config::Bind(DebuggerAuthTokenScriptBin, ini, config, "Eval.Debugger.Auth.TokenScriptBin"); Config::Bind(DebuggerSessionAuthScriptBin, ini, config, "Eval.Debugger.Auth.SessionAuthScriptBin"); } } { // CodeCache using jit::CodeCache; Config::Bind(CodeCache::AHotSize, ini, config, "Eval.JitAHotSize", ahotDefault()); Config::Bind(CodeCache::ASize, ini, config, "Eval.JitASize", 60 << 20); Config::Bind(CodeCache::AProfSize, ini, config, "Eval.JitAProfSize", RuntimeOption::EvalJitPGO ? (64 << 20) : 0); Config::Bind(CodeCache::AColdSize, ini, config, "Eval.JitAColdSize", 24 << 20); Config::Bind(CodeCache::AFrozenSize, ini, config, "Eval.JitAFrozenSize", 40 << 20); Config::Bind(CodeCache::ABytecodeSize, ini, config, "Eval.JitABytecodeSize", 0); Config::Bind(CodeCache::GlobalDataSize, ini, config, "Eval.JitGlobalDataSize", CodeCache::ASize >> 2); Config::Bind(CodeCache::MapTCHuge, ini, config, "Eval.MapTCHuge", hugePagesSoundNice()); Config::Bind(CodeCache::TCNumHugeHotMB, ini, config, "Eval.TCNumHugeHotMB", 64); Config::Bind(CodeCache::TCNumHugeMainMB, ini, config, "Eval.TCNumHugeMainMB", 16); Config::Bind(CodeCache::TCNumHugeColdMB, ini, config, "Eval.TCNumHugeColdMB", 4); Config::Bind(CodeCache::AutoTCShift, ini, config, "Eval.JitAutoTCShift", 1); } { // Hack Language Config::Bind(CheckIntOverflow, ini, config, "Hack.Lang.CheckIntOverflow", 0); Config::Bind(StrictArrayFillKeys, ini, config, "Hack.Lang.StrictArrayFillKeys", HackStrictOption::ON); Config::Bind(LookForTypechecker, ini, config, "Hack.Lang.LookForTypechecker", false); // If you turn off LookForTypechecker, you probably want to turn this off // too -- basically, make the two look like the same option to external // users, unless you really explicitly want to set them differently for // some reason. Config::Bind(AutoTypecheck, ini, config, "Hack.Lang.AutoTypecheck", LookForTypechecker); Config::Bind(EnableClassLevelWhereClauses, ini, config, "Hack.Lang.EnableClassLevelWhereClauses", false); } { // Options for PHP7 features which break BC. (Features which do not break // BC don't need options here and can just always be turned on.) // // NB that the "PHP7.all" option is intended to be only a master switch; // all runtime behavior gating should be based on sub-options (that's why // it's a file static not a static member of RuntimeOption). Also don't // forget to update mangleUnitPHP7Options if needed. // // TODO: we may eventually want to make an option which specifies // directories or filenames to exclude from PHP7 behavior, and so checking // these may want to be per-file. We originally planned to do this from the // get-go, but threading that through turns out to be kind of annoying and // of questionable value, so just doing this for now. Config::Bind(s_PHP7_master, ini, config, "PHP7.all", s_PHP7_default); Config::Bind(PHP7_EngineExceptions, ini, config, "PHP7.EngineExceptions", s_PHP7_master); Config::Bind(PHP7_NoHexNumerics, ini, config, "PHP7.NoHexNumerics", s_PHP7_master); Config::Bind(PHP7_Builtins, ini, config, "PHP7.Builtins", s_PHP7_master); Config::Bind(PHP7_Substr, ini, config, "PHP7.Substr", s_PHP7_master); Config::Bind(PHP7_DisallowUnsafeCurlUploads, ini, config, "PHP7.DisallowUnsafeCurlUploads", s_PHP7_master); } { // Server Config::Bind(Host, ini, config, "Server.Host"); Config::Bind(DefaultServerNameSuffix, ini, config, "Server.DefaultServerNameSuffix"); Config::Bind(AlwaysDecodePostDataDefault, ini, config, "Server.AlwaysDecodePostDataDefault", AlwaysDecodePostDataDefault); Config::Bind(ServerType, ini, config, "Server.Type", ServerType); Config::Bind(ServerIP, ini, config, "Server.IP"); Config::Bind(ServerFileSocket, ini, config, "Server.FileSocket"); #ifdef FACEBOOK //Do not cause slowness on startup -- except for Facebook if (GetServerPrimaryIPv4().empty() && GetServerPrimaryIPv6().empty()) { throw std::runtime_error("Unable to resolve the server's " "IPv4 or IPv6 address"); } #endif Config::Bind(ServerPort, ini, config, "Server.Port", 80); Config::Bind(ServerBacklog, ini, config, "Server.Backlog", 128); Config::Bind(ServerConnectionLimit, ini, config, "Server.ConnectionLimit", 0); Config::Bind(ServerThreadCount, ini, config, "Server.ThreadCount", Process::GetCPUCount() * 2); Config::Bind(ServerQueueCount, ini, config, "Server.QueueCount", ServerThreadCount); Config::Bind(ServerIOThreadCount, ini, config, "Server.IOThreadCount", 1); Config::Bind(ServerLegacyBehavior, ini, config, "Server.LegacyBehavior", ServerLegacyBehavior); Config::Bind(ServerHugeThreadCount, ini, config, "Server.HugeThreadCount", 0); Config::Bind(ServerHugeStackKb, ini, config, "Server.HugeStackSizeKb", 384); Config::Bind(ServerLoopSampleRate, ini, config, "Server.LoopSampleRate", 0); Config::Bind(ServerWarmupThrottleRequestCount, ini, config, "Server.WarmupThrottleRequestCount", ServerWarmupThrottleRequestCount); Config::Bind(ServerWarmupThrottleThreadCount, ini, config, "Server.WarmupThrottleThreadCount", Process::GetCPUCount()); Config::Bind(ServerThreadDropCacheTimeoutSeconds, ini, config, "Server.ThreadDropCacheTimeoutSeconds", 0); if (Config::GetBool(ini, config, "Server.ThreadJobLIFO")) { ServerThreadJobLIFOSwitchThreshold = 0; } Config::Bind(ServerThreadJobLIFOSwitchThreshold, ini, config, "Server.ThreadJobLIFOSwitchThreshold", ServerThreadJobLIFOSwitchThreshold); Config::Bind(ServerThreadJobMaxQueuingMilliSeconds, ini, config, "Server.ThreadJobMaxQueuingMilliSeconds", -1); Config::Bind(ServerThreadDropStack, ini, config, "Server.ThreadDropStack"); Config::Bind(ServerHttpSafeMode, ini, config, "Server.HttpSafeMode"); Config::Bind(ServerStatCache, ini, config, "Server.StatCache", false); Config::Bind(ServerFixPathInfo, ini, config, "Server.FixPathInfo", false); Config::Bind(ServerAddVaryEncoding, ini, config, "Server.AddVaryEncoding", ServerAddVaryEncoding); Config::Bind(ServerLogSettingsOnStartup, ini, config, "Server.LogSettingsOnStartup", false); Config::Bind(ServerLogReorderProps, ini, config, "Server.LogReorderProps", false); Config::Bind(ServerWarmupConcurrently, ini, config, "Server.WarmupConcurrently", false); Config::Bind(ServerDedupeWarmupRequests, ini, config, "Server.DedupeWarmupRequests", false); Config::Bind(ServerWarmupThreadCount, ini, config, "Server.WarmupThreadCount", ServerWarmupThreadCount); Config::Bind(ServerExtendedWarmupThreadCount, ini, config, "Server.ExtendedWarmup.ThreadCount", ServerExtendedWarmupThreadCount); Config::Bind(ServerExtendedWarmupDelaySeconds, ini, config, "Server.ExtendedWarmup.DelaySeconds", ServerExtendedWarmupDelaySeconds); Config::Bind(ServerExtendedWarmupRepeat, ini, config, "Server.ExtendedWarmup.Repeat", ServerExtendedWarmupRepeat); Config::Bind(ServerWarmupRequests, ini, config, "Server.WarmupRequests"); Config::Bind(ServerExtendedWarmupRequests, ini, config, "Server.ExtendedWarmup.Requests"); Config::Bind(ServerCleanupRequest, ini, config, "Server.CleanupRequest"); Config::Bind(ServerInternalWarmupThreads, ini, config, "Server.InternalWarmupThreads", 0); // 0 = skip Config::Bind(ServerHighPriorityEndPoints, ini, config, "Server.HighPriorityEndPoints"); Config::Bind(ServerExitOnBindFail, ini, config, "Server.ExitOnBindFail", false); Config::Bind(RequestTimeoutSeconds, ini, config, "Server.RequestTimeoutSeconds", 0); Config::Bind(MaxRequestAgeFactor, ini, config, "Server.MaxRequestAgeFactor", 0); Config::Bind(PspTimeoutSeconds, ini, config, "Server.PspTimeoutSeconds", 0); Config::Bind(PspCpuTimeoutSeconds, ini, config, "Server.PspCpuTimeoutSeconds", 0); Config::Bind(RequestMemoryMaxBytes, ini, config, "Server.RequestMemoryMaxBytes", (16LL << 30)); // 16GiB RequestInfo::setOOMKillThreshold( Config::GetUInt64(ini, config, "Server.RequestMemoryOOMKillBytes", 128ULL << 20)); Config::Bind(RequestHugeMaxBytes, ini, config, "Server.RequestHugeMaxBytes", (24LL << 20)); Config::Bind(ServerGracefulShutdownWait, ini, config, "Server.GracefulShutdownWait", 0); Config::Bind(ServerHarshShutdown, ini, config, "Server.HarshShutdown", true); Config::Bind(ServerKillOnTimeout, ini, config, "Server.KillOnTimeout", true); Config::Bind(ServerEvilShutdown, ini, config, "Server.EvilShutdown", true); Config::Bind(ServerPreShutdownWait, ini, config, "Server.PreShutdownWait", 0); Config::Bind(ServerShutdownListenWait, ini, config, "Server.ShutdownListenWait", 0); Config::Bind(ServerShutdownEOMWait, ini, config, "Server.ShutdownEOMWait", 0); Config::Bind(ServerPrepareToStopTimeout, ini, config, "Server.PrepareToStopTimeout", 240); Config::Bind(ServerPartialPostStatusCode, ini, config, "Server.PartialPostStatusCode", -1); Config::Bind(StopOldServer, ini, config, "Server.StopOld", false); Config::Bind(OldServerWait, ini, config, "Server.StopOldWait", 30); Config::Bind(ServerRSSNeededMb, ini, config, "Server.RSSNeededMb", 4096); Config::Bind(ServerCriticalFreeMb, ini, config, "Server.CriticalFreeMb", 512); Config::Bind(CacheFreeFactor, ini, config, "Server.CacheFreeFactor", 50); if (CacheFreeFactor > 100) CacheFreeFactor = 100; if (CacheFreeFactor < 0) CacheFreeFactor = 0; Config::Bind(ServerNextProtocols, ini, config, "Server.SSLNextProtocols"); Config::Bind(ServerEnableH2C, ini, config, "Server.EnableH2C"); extern bool g_brotliUseLocalArena; Config::Bind(g_brotliUseLocalArena, ini, config, "Server.BrotliUseLocalArena", g_brotliUseLocalArena); Config::Bind(BrotliCompressionEnabled, ini, config, "Server.BrotliCompressionEnabled", -1); Config::Bind(BrotliChunkedCompressionEnabled, ini, config, "Server.BrotliChunkedCompressionEnabled", -1); Config::Bind(BrotliCompressionLgWindowSize, ini, config, "Server.BrotliCompressionLgWindowSize", 20); Config::Bind(BrotliCompressionMode, ini, config, "Server.BrotliCompressionMode", 0); Config::Bind(BrotliCompressionQuality, ini, config, "Server.BrotliCompressionQuality", 6); Config::Bind(ZstdCompressionEnabled, ini, config, "Server.ZstdCompressionEnabled", -1); Config::Bind(ZstdCompressor::s_useLocalArena, ini, config, "Server.ZstdUseLocalArena", ZstdCompressor::s_useLocalArena); Config::Bind(ZstdCompressionLevel, ini, config, "Server.ZstdCompressionLevel", 3); Config::Bind(ZstdChecksumRate, ini, config, "Server.ZstdChecksumRate", 0); Config::Bind(GzipCompressionLevel, ini, config, "Server.GzipCompressionLevel", 3); Config::Bind(GzipMaxCompressionLevel, ini, config, "Server.GzipMaxCompressionLevel", 9); Config::Bind(GzipCompressor::s_useLocalArena, ini, config, "Server.GzipUseLocalArena", GzipCompressor::s_useLocalArena); Config::Bind(EnableKeepAlive, ini, config, "Server.EnableKeepAlive", true); Config::Bind(ExposeHPHP, ini, config, "Server.ExposeHPHP", true); Config::Bind(ExposeXFBServer, ini, config, "Server.ExposeXFBServer", false); Config::Bind(ExposeXFBDebug, ini, config, "Server.ExposeXFBDebug", false); Config::Bind(XFBDebugSSLKey, ini, config, "Server.XFBDebugSSLKey", ""); Config::Bind(ConnectionTimeoutSeconds, ini, config, "Server.ConnectionTimeoutSeconds", -1); Config::Bind(EnableOutputBuffering, ini, config, "Server.EnableOutputBuffering"); Config::Bind(OutputHandler, ini, config, "Server.OutputHandler"); Config::Bind(ImplicitFlush, ini, config, "Server.ImplicitFlush"); Config::Bind(EnableEarlyFlush, ini, config, "Server.EnableEarlyFlush", true); Config::Bind(ForceChunkedEncoding, ini, config, "Server.ForceChunkedEncoding"); Config::Bind(MaxPostSize, ini, config, "Server.MaxPostSize", 100); MaxPostSize <<= 20; Config::Bind(AlwaysPopulateRawPostData, ini, config, "Server.AlwaysPopulateRawPostData", false); Config::Bind(TakeoverFilename, ini, config, "Server.TakeoverFilename"); Config::Bind(ExpiresActive, ini, config, "Server.ExpiresActive", true); Config::Bind(ExpiresDefault, ini, config, "Server.ExpiresDefault", 2592000); if (ExpiresDefault < 0) ExpiresDefault = 2592000; Config::Bind(DefaultCharsetName, ini, config, "Server.DefaultCharsetName", ""); Config::Bind(RequestBodyReadLimit, ini, config, "Server.RequestBodyReadLimit", -1); Config::Bind(EnableSSL, ini, config, "Server.EnableSSL"); Config::Bind(SSLPort, ini, config, "Server.SSLPort", 443); Config::Bind(SSLCertificateFile, ini, config, "Server.SSLCertificateFile"); Config::Bind(SSLCertificateKeyFile, ini, config, "Server.SSLCertificateKeyFile"); Config::Bind(SSLCertificateDir, ini, config, "Server.SSLCertificateDir"); Config::Bind(SSLTicketSeedFile, ini, config, "Server.SSLTicketSeedFile"); Config::Bind(TLSDisableTLS1_2, ini, config, "Server.TLSDisableTLS1_2", false); Config::Bind(TLSClientCipherSpec, ini, config, "Server.TLSClientCipherSpec"); Config::Bind(EnableSSLWithPlainText, ini, config, "Server.EnableSSLWithPlainText"); Config::Bind(SSLClientAuthLevel, ini, config, "Server.SSLClientAuthLevel", 0); if (SSLClientAuthLevel < 0) SSLClientAuthLevel = 0; if (SSLClientAuthLevel > 2) SSLClientAuthLevel = 2; Config::Bind(SSLClientCAFile, ini, config, "Server.SSLClientCAFile", ""); if (!SSLClientAuthLevel) { SSLClientCAFile = ""; } else if (SSLClientCAFile.empty()) { throw std::runtime_error( "SSLClientCAFile is required to enable client auth"); } Config::Bind(ClientAuthAclIdentity, ini, config, "Server.ClientAuthAclIdentity", ""); Config::Bind(ClientAuthAclAction, ini, config, "Server.ClientAuthAclAction", ""); Config::Bind(ClientAuthFailClose, ini, config, "Server.ClientAuthFailClose", false); Config::Bind(ClientAuthLogSampleBase, ini, config, "Server.ClientAuthLogSampleBase", 100); if (ClientAuthLogSampleBase < 1) { ClientAuthLogSampleBase = 1; } Config::Bind(SSLClientAuthLoggingSampleRatio, ini, config, "Server.SSLClientAuthLoggingSampleRatio", 0); if (SSLClientAuthLoggingSampleRatio < 0) { SSLClientAuthLoggingSampleRatio = 0; } if (SSLClientAuthLoggingSampleRatio > ClientAuthLogSampleBase) { SSLClientAuthLoggingSampleRatio = ClientAuthLogSampleBase; } Config::Bind(ClientAuthSuccessLogSampleRatio, ini, config, "Server.ClientAuthSuccessLogSampleRatio", 0); if (ClientAuthSuccessLogSampleRatio < SSLClientAuthLoggingSampleRatio) { ClientAuthSuccessLogSampleRatio = SSLClientAuthLoggingSampleRatio; } if (ClientAuthSuccessLogSampleRatio > ClientAuthLogSampleBase) { ClientAuthSuccessLogSampleRatio = ClientAuthLogSampleBase; } Config::Bind(ClientAuthFailureLogSampleRatio, ini, config, "Server.ClientAuthFailureLogSampleRatio", 0); if (ClientAuthFailureLogSampleRatio < SSLClientAuthLoggingSampleRatio) { ClientAuthFailureLogSampleRatio = SSLClientAuthLoggingSampleRatio; } if (ClientAuthFailureLogSampleRatio > ClientAuthLogSampleBase) { ClientAuthFailureLogSampleRatio = ClientAuthLogSampleBase; } // SourceRoot has been default to: Process::GetCurrentDirectory() + '/' auto defSourceRoot = SourceRoot; Config::Bind(SourceRoot, ini, config, "Server.SourceRoot", SourceRoot); SourceRoot = FileUtil::normalizeDir(SourceRoot); if (SourceRoot.empty()) { SourceRoot = defSourceRoot; } FileCache::SourceRoot = SourceRoot; Config::Bind(IncludeSearchPaths, ini, config, "Server.IncludeSearchPaths"); for (unsigned int i = 0; i < IncludeSearchPaths.size(); i++) { IncludeSearchPaths[i] = FileUtil::normalizeDir(IncludeSearchPaths[i]); } IncludeSearchPaths.insert(IncludeSearchPaths.begin(), "."); Config::Bind(AutoloadEnabled, ini, config, "Autoload.Enabled", false); Config::Bind(AutoloadDBPath, ini, config, "Autoload.DBPath"); Config::Bind(FileCache, ini, config, "Server.FileCache"); Config::Bind(DefaultDocument, ini, config, "Server.DefaultDocument", "index.php"); Config::Bind(GlobalDocument, ini, config, "Server.GlobalDocument"); Config::Bind(ErrorDocument404, ini, config, "Server.ErrorDocument404"); normalizePath(ErrorDocument404); Config::Bind(ForbiddenAs404, ini, config, "Server.ForbiddenAs404"); Config::Bind(ErrorDocument500, ini, config, "Server.ErrorDocument500"); normalizePath(ErrorDocument500); Config::Bind(FatalErrorMessage, ini, config, "Server.FatalErrorMessage"); FontPath = FileUtil::normalizeDir( Config::GetString(ini, config, "Server.FontPath")); Config::Bind(EnableStaticContentFromDisk, ini, config, "Server.EnableStaticContentFromDisk", true); Config::Bind(EnableOnDemandUncompress, ini, config, "Server.EnableOnDemandUncompress", true); Config::Bind(EnableStaticContentMMap, ini, config, "Server.EnableStaticContentMMap", true); if (EnableStaticContentMMap) { EnableOnDemandUncompress = true; } Config::Bind(Utf8izeReplace, ini, config, "Server.Utf8izeReplace", true); Config::Bind(RequestInitFunction, ini, config, "Server.RequestInitFunction"); Config::Bind(RequestInitDocument, ini, config, "Server.RequestInitDocument"); Config::Bind(SafeFileAccess, ini, config, "Server.SafeFileAccess"); Config::Bind(AllowedDirectories, ini, config, "Server.AllowedDirectories"); Config::Bind(WhitelistExec, ini, config, "Server.WhitelistExec"); Config::Bind(WhitelistExecWarningOnly, ini, config, "Server.WhitelistExecWarningOnly"); Config::Bind(AllowedExecCmds, ini, config, "Server.AllowedExecCmds"); Config::Bind(UnserializationWhitelistCheck, ini, config, "Server.UnserializationWhitelistCheck", false); Config::Bind(UnserializationWhitelistCheckWarningOnly, ini, config, "Server.UnserializationWhitelistCheckWarningOnly", true); Config::Bind(UnserializationBigMapThreshold, ini, config, "Server.UnserializationBigMapThreshold", 1 << 16); Config::Bind(AllowedFiles, ini, config, "Server.AllowedFiles"); Config::Bind(ForbiddenFileExtensions, ini, config, "Server.ForbiddenFileExtensions"); Config::Bind(LockCodeMemory, ini, config, "Server.LockCodeMemory", false); Config::Bind(MaxArrayChain, ini, config, "Server.MaxArrayChain", INT_MAX); if (MaxArrayChain != INT_MAX) { // MixedArray needs a higher threshold to avoid false-positives. // (and we always use MixedArray) MaxArrayChain *= 2; } Config::Bind(WarnOnCollectionToArray, ini, config, "Server.WarnOnCollectionToArray", false); Config::Bind(UseDirectCopy, ini, config, "Server.UseDirectCopy", false); Config::Bind(AlwaysUseRelativePath, ini, config, "Server.AlwaysUseRelativePath", false); { // Server Upload Config::Bind(UploadMaxFileSize, ini, config, "Server.Upload.UploadMaxFileSize", 100); UploadMaxFileSize <<= 20; Config::Bind(UploadTmpDir, ini, config, "Server.Upload.UploadTmpDir", "/tmp"); Config::Bind(EnableFileUploads, ini, config, "Server.Upload.EnableFileUploads", true); Config::Bind(MaxFileUploads, ini, config, "Server.Upload.MaxFileUploads", 20); Config::Bind(EnableUploadProgress, ini, config, "Server.Upload.EnableUploadProgress"); Config::Bind(Rfc1867Freq, ini, config, "Server.Upload.Rfc1867Freq", 256 * 1024); if (Rfc1867Freq < 0) Rfc1867Freq = 256 * 1024; Config::Bind(Rfc1867Prefix, ini, config, "Server.Upload.Rfc1867Prefix", "vupload_"); Config::Bind(Rfc1867Name, ini, config, "Server.Upload.Rfc1867Name", "video_ptoken"); } Config::Bind(ImageMemoryMaxBytes, ini, config, "Server.ImageMemoryMaxBytes", 0); if (ImageMemoryMaxBytes == 0) { ImageMemoryMaxBytes = UploadMaxFileSize * 2; } Config::Bind(LightProcessFilePrefix, ini, config, "Server.LightProcessFilePrefix", "./lightprocess"); Config::Bind(LightProcessCount, ini, config, "Server.LightProcessCount", 0); Config::Bind(LightProcess::g_strictUser, ini, config, "Server.LightProcessStrictUser", false); Config::Bind(ForceServerNameToHeader, ini, config, "Server.ForceServerNameToHeader"); Config::Bind(AllowDuplicateCookies, ini, config, "Server.AllowDuplicateCookies", false); Config::Bind(PathDebug, ini, config, "Server.PathDebug", false); Config::Bind(ServerUser, ini, config, "Server.User", ""); Config::Bind(AllowRunAsRoot, ini, config, "Server.AllowRunAsRoot", false); } VirtualHost::SortAllowedDirectories(AllowedDirectories); { auto vh_callback = [] (const IniSettingMap &ini_vh, const Hdf &hdf_vh, const std::string &ini_vh_key) { if (VirtualHost::IsDefault(ini_vh, hdf_vh, ini_vh_key)) { VirtualHost::GetDefault().init(ini_vh, hdf_vh, ini_vh_key); VirtualHost::GetDefault().addAllowedDirectories(AllowedDirectories); } else { auto host = std::make_shared<VirtualHost>(ini_vh, hdf_vh, ini_vh_key); host->addAllowedDirectories(AllowedDirectories); VirtualHosts.push_back(host); } }; // Virtual Hosts have to be iterated in order. Because only the first // one that matches in the VirtualHosts vector gets applied and used. // Hdf's and ini (via Variant arrays) internal storage handles ordering // naturally (as specified top to bottom in the file and left to right on // the command line. Config::Iterate(vh_callback, ini, config, "VirtualHost"); LowestMaxPostSize = VirtualHost::GetLowestMaxPostSize(); } { // IpBlocks IpBlocks = std::make_shared<IpBlockMap>(ini, config); } { ReadSatelliteInfo(ini, config, SatelliteServerInfos, XboxPassword, XboxPasswords); } { // Xbox Config::Bind(XboxServerThreadCount, ini, config, "Xbox.ServerInfo.ThreadCount", 10); Config::Bind(XboxServerMaxQueueLength, ini, config, "Xbox.ServerInfo.MaxQueueLength", INT_MAX); if (XboxServerMaxQueueLength < 0) XboxServerMaxQueueLength = INT_MAX; Config::Bind(XboxServerInfoMaxRequest, ini, config, "Xbox.ServerInfo.MaxRequest", 500); Config::Bind(XboxServerInfoDuration, ini, config, "Xbox.ServerInfo.MaxDuration", 120); Config::Bind(XboxServerInfoReqInitFunc, ini, config, "Xbox.ServerInfo.RequestInitFunction", ""); Config::Bind(XboxServerInfoReqInitDoc, ini, config, "Xbox.ServerInfo.RequestInitDocument", ""); Config::Bind(XboxServerInfoAlwaysReset, ini, config, "Xbox.ServerInfo.AlwaysReset", false); Config::Bind(XboxServerLogInfo, ini, config, "Xbox.ServerInfo.LogInfo", false); Config::Bind(XboxProcessMessageFunc, ini, config, "Xbox.ProcessMessageFunc", "xbox_process_message"); } { // Pagelet Server Config::Bind(PageletServerThreadCount, ini, config, "PageletServer.ThreadCount", 0); Config::Bind(PageletServerHugeThreadCount, ini, config, "PageletServer.HugeThreadCount", 0); Config::Bind(PageletServerThreadDropStack, ini, config, "PageletServer.ThreadDropStack"); Config::Bind(PageletServerThreadDropCacheTimeoutSeconds, ini, config, "PageletServer.ThreadDropCacheTimeoutSeconds", 0); Config::Bind(PageletServerQueueLimit, ini, config, "PageletServer.QueueLimit", 0); } { // Static File hphp_string_imap<std::string> staticFileDefault; staticFileDefault["css"] = "text/css"; staticFileDefault["gif"] = "image/gif"; staticFileDefault["html"] = "text/html"; staticFileDefault["jpeg"] = "image/jpeg"; staticFileDefault["jpg"] = "image/jpeg"; staticFileDefault["mp3"] = "audio/mpeg"; staticFileDefault["png"] = "image/png"; staticFileDefault["tif"] = "image/tiff"; staticFileDefault["tiff"] = "image/tiff"; staticFileDefault["txt"] = "text/plain"; staticFileDefault["zip"] = "application/zip"; Config::Bind(StaticFileExtensions, ini, config, "StaticFile.Extensions", staticFileDefault); auto matches_callback = [](const IniSettingMap& ini_m, const Hdf& hdf_m, const std::string& /*ini_m_key*/) { FilesMatches.push_back(std::make_shared<FilesMatch>(ini_m, hdf_m)); }; Config::Iterate(matches_callback, ini, config, "StaticFile.FilesMatch"); } { // PhpFile Config::Bind(PhpFileExtensions, ini, config, "PhpFile.Extensions"); } { // Admin Server Config::Bind(AdminServerIP, ini, config, "AdminServer.IP", ServerIP); Config::Bind(AdminServerPort, ini, config, "AdminServer.Port", 0); Config::Bind(AdminThreadCount, ini, config, "AdminServer.ThreadCount", 1); Config::Bind(AdminServerEnableSSLWithPlainText, ini, config, "AdminServer.EnableSSLWithPlainText", false); Config::Bind(AdminServerStatsNeedPassword, ini, config, "AdminServer.StatsNeedPassword", AdminServerStatsNeedPassword); AdminPassword = Config::GetString(ini, config, "AdminServer.Password"); AdminPasswords = Config::GetSet(ini, config, "AdminServer.Passwords"); HashedAdminPasswords = Config::GetSet(ini, config, "AdminServer.HashedPasswords"); Config::Bind(AdminDumpPath, ini, config, "AdminServer.DumpPath", "/tmp/hhvm_admin_dump"); } { // Proxy Config::Bind(ProxyOriginRaw, ini, config, "Proxy.Origin"); Config::Bind(ProxyPercentageRaw, ini, config, "Proxy.Percentage", 0); Config::Bind(ProxyRetry, ini, config, "Proxy.Retry", 3); Config::Bind(UseServeURLs, ini, config, "Proxy.ServeURLs"); Config::Bind(ServeURLs, ini, config, "Proxy.ServeURLs"); Config::Bind(UseProxyURLs, ini, config, "Proxy.ProxyURLs"); Config::Bind(ProxyURLs, ini, config, "Proxy.ProxyURLs"); Config::Bind(ProxyPatterns, ini, config, "Proxy.ProxyPatterns"); } { // Http Config::Bind(HttpDefaultTimeout, ini, config, "Http.DefaultTimeout", 30); Config::Bind(HttpSlowQueryThreshold, ini, config, "Http.SlowQueryThreshold", 5000); } { // Debug Config::Bind(NativeStackTrace, ini, config, "Debug.NativeStackTrace"); StackTrace::Enabled = NativeStackTrace; Config::Bind(ServerErrorMessage, ini, config, "Debug.ServerErrorMessage"); Config::Bind(RecordInput, ini, config, "Debug.RecordInput"); Config::Bind(ClearInputOnSuccess, ini, config, "Debug.ClearInputOnSuccess", true); Config::Bind(ProfilerOutputDir, ini, config, "Debug.ProfilerOutputDir", "/tmp"); Config::Bind(CoreDumpEmail, ini, config, "Debug.CoreDumpEmail"); Config::Bind(CoreDumpReport, ini, config, "Debug.CoreDumpReport", true); if (CoreDumpReport) { install_crash_reporter(); } // Binding default dependenant on whether we are using an OSS build or // not, and that is set at initialization time of CoreDumpReportDirectory. Config::Bind(CoreDumpReportDirectory, ini, config, "Debug.CoreDumpReportDirectory", CoreDumpReportDirectory); std::ostringstream stack_trace_stream; stack_trace_stream << CoreDumpReportDirectory << "/stacktrace." << (int64_t)getpid() << ".log"; StackTraceFilename = stack_trace_stream.str(); Config::Bind(StackTraceTimeout, ini, config, "Debug.StackTraceTimeout", 0); Config::Bind(RemoteTraceOutputDir, ini, config, "Debug.RemoteTraceOutputDir", "/tmp"); Config::Bind(TraceFunctions, ini, config, "Debug.TraceFunctions", TraceFunctions); } { // Stats Config::Bind(EnableStats, ini, config, "Stats.Enable", false); // main switch Config::Bind(EnableAPCStats, ini, config, "Stats.APC", false); Config::Bind(EnableWebStats, ini, config, "Stats.Web"); Config::Bind(EnableMemoryStats, ini, config, "Stats.Memory"); Config::Bind(EnableSQLStats, ini, config, "Stats.SQL"); Config::Bind(EnableSQLTableStats, ini, config, "Stats.SQLTable"); Config::Bind(EnableNetworkIOStatus, ini, config, "Stats.NetworkIO"); Config::Bind(StatsXSL, ini, config, "Stats.XSL"); Config::Bind(StatsXSLProxy, ini, config, "Stats.XSLProxy"); Config::Bind(StatsSlotDuration, ini, config, "Stats.SlotDuration", 10 * 60); Config::Bind(StatsMaxSlot, ini, config, "Stats.MaxSlot", 12 * 6); // 12 hours StatsSlotDuration = std::max(1u, StatsSlotDuration); StatsMaxSlot = std::max(2u, StatsMaxSlot); Config::Bind(EnableHotProfiler, ini, config, "Stats.EnableHotProfiler", true); Config::Bind(ProfilerTraceBuffer, ini, config, "Stats.ProfilerTraceBuffer", 2000000); Config::Bind(ProfilerTraceExpansion, ini, config, "Stats.ProfilerTraceExpansion", 1.2); Config::Bind(ProfilerMaxTraceBuffer, ini, config, "Stats.ProfilerMaxTraceBuffer", 0); Config::Bind(TrackPerUnitMemory, ini, config, "Stats.TrackPerUnitMemory", false); } { Config::Bind(ServerVariables, ini, config, "ServerVariables"); Config::Bind(EnvVariables, ini, config, "EnvVariables"); } { // Sandbox Config::Bind(SandboxMode, ini, config, "Sandbox.SandboxMode"); Config::Bind(SandboxPattern, ini, config, "Sandbox.Pattern"); SandboxPattern = format_pattern(SandboxPattern, true); Config::Bind(SandboxHome, ini, config, "Sandbox.Home"); Config::Bind(SandboxFallback, ini, config, "Sandbox.Fallback"); Config::Bind(SandboxConfFile, ini, config, "Sandbox.ConfFile"); Config::Bind(SandboxFromCommonRoot, ini, config, "Sandbox.FromCommonRoot"); Config::Bind(SandboxDirectoriesRoot, ini, config, "Sandbox.DirectoriesRoot"); Config::Bind(SandboxLogsRoot, ini, config, "Sandbox.LogsRoot"); Config::Bind(SandboxServerVariables, ini, config, "Sandbox.ServerVariables"); Config::Bind(SandboxDefaultUserFile, ini, config, "Sandbox.DefaultUserFile"); Config::Bind(SandboxHostAlias, ini, config, "Sandbox.HostAlias"); } { // Mail Config::Bind(SendmailPath, ini, config, "Mail.SendmailPath", "/usr/lib/sendmail -t -i"); Config::Bind(MailForceExtraParameters, ini, config, "Mail.ForceExtraParameters"); } { // Preg Config::Bind(PregBacktraceLimit, ini, config, "Preg.BacktraceLimit", 1000000); Config::Bind(PregRecursionLimit, ini, config, "Preg.RecursionLimit", 100000); Config::Bind(EnablePregErrorLog, ini, config, "Preg.ErrorLog", true); } { // SimpleXML Config::Bind(SimpleXMLEmptyNamespaceMatchesAll, ini, config, "SimpleXML.EmptyNamespaceMatchesAll", false); } #ifdef FACEBOOK { // Fb303Server Config::Bind(EnableFb303Server, ini, config, "Fb303Server.Enable", EnableFb303Server); Config::Bind(Fb303ServerPort, ini, config, "Fb303Server.Port", 0); Config::Bind(Fb303ServerIP, ini, config, "Fb303Server.IP"); Config::Bind(Fb303ServerThreadStackSizeMb, ini, config, "Fb303Server.ThreadStackSizeMb", 8); Config::Bind(Fb303ServerWorkerThreads, ini, config, "Fb303Server.WorkerThreads", 1); Config::Bind(Fb303ServerPoolThreads, ini, config, "Fb303Server.PoolThreads", 1); } #endif { // Xenon Config::Bind(XenonPeriodSeconds, ini, config, "Xenon.Period", 0.0); Config::Bind(XenonRequestFreq, ini, config, "Xenon.RequestFreq", 1); Config::Bind(XenonForceAlwaysOn, ini, config, "Xenon.ForceAlwaysOn", false); } { // Strobelight Config::Bind(StrobelightEnabled, ini, config, "Strobelight.Enabled", false); } { // Profiling Config::Bind(SetProfileNullThisObject, ini, config, "SetProfile.NullThisObject", true); } { // We directly read zend.assertions here, so that we can get its INI value // in order to know how we should emit bytecode. We don't actually Bind the // option here though, since its runtime value can be changed and is per // request. (We prevent its value from changing at runtime between values // that would affect byecode emission.) Variant v; bool b = IniSetting::GetSystem("zend.assertions", v); if (b) RuntimeOption::AssertEmitted = v.toInt64() >= 0; } Config::Bind(TzdataSearchPaths, ini, config, "TzdataSearchPaths"); Config::Bind(CustomSettings, ini, config, "CustomSettings"); // Run initializers depedent on options, e.g., resizing atomic maps/vectors. refineStaticStringTableSize(); InitFiniNode::ProcessPostRuntimeOptions(); // ************************************************************************** // DANGER // // Do not bind any PHP_INI_ALL or PHP_INI_USER settings here! These settings // are process-wide, while those need to be thread-local since they are // per-request. They should go into RequestInjectionData. Getting this wrong // will cause subtle breakage -- in particular, it probably will not show up // in CLI mode, since everything there tends to be single theaded. // // Per-dir INI settings are bound here, but that seems really questionable // since they can change per request too. TODO(#7757602) this should be // investigated. // ************************************************************************** // Enables the hotfixing of a bug that occurred with D1797805 where // per request user settings (like upload_max_filesize) were not able to be // accessed on a server request any longer. The longer term fix is in review // D2099778, but we want that to simmer in Master for a while and we need // a hotfix for our current 3.6 LTS (Github Issue #4993) Config::Bind(EnableZendIniCompat, ini, config, "Eval.EnableZendIniCompat", true); // Language and Misc Configuration Options IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_ONLY, "expose_php", &RuntimeOption::ExposeHPHP); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_PERDIR, "auto_prepend_file", &RuntimeOption::AutoPrependFile); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_PERDIR, "auto_append_file", &RuntimeOption::AutoAppendFile); // Data Handling IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_PERDIR, "post_max_size", IniSetting::SetAndGet<int64_t>( nullptr, []() { return VirtualHost::GetMaxPostSize(); } ), &RuntimeOption::MaxPostSize); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_PERDIR, "always_populate_raw_post_data", &RuntimeOption::AlwaysPopulateRawPostData); // Paths and Directories IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_SYSTEM, "doc_root", &RuntimeOption::SourceRoot); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_SYSTEM, "sendmail_path", &RuntimeOption::SendmailPath); // FastCGI IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_ONLY, "pid", &RuntimeOption::PidFile); // File Uploads IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_SYSTEM, "file_uploads", "true", &RuntimeOption::EnableFileUploads); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_SYSTEM, "upload_tmp_dir", &RuntimeOption::UploadTmpDir); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_PERDIR, "upload_max_filesize", IniSetting::SetAndGet<std::string>( [](const std::string& value) { return ini_on_update( value, RuntimeOption::UploadMaxFileSize); }, []() { return convert_long_to_bytes( VirtualHost::GetUploadMaxFileSize()); } )); // Filesystem and Streams Configuration Options IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_SYSTEM, "allow_url_fopen", IniSetting::SetAndGet<std::string>( [](const std::string& /*value*/) { return false; }, []() { return "1"; })); // HPHP specific IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_NONE, "hphp.compiler_id", IniSetting::SetAndGet<std::string>( [](const std::string& /*value*/) { return false; }, []() { return compilerId().begin(); })); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_NONE, "hphp.compiler_version", IniSetting::SetAndGet<std::string>( [](const std::string& /*value*/) { return false; }, []() { return getHphpCompilerVersion(); })); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_NONE, "hphp.cli_server_api_version", IniSetting::SetAndGet<uint64_t>( [](const uint64_t /*value*/) { return false; }, []() { return cli_server_api_version(); })); IniSetting::Bind( IniSetting::CORE, IniSetting::PHP_INI_NONE, "hphp.build_id", IniSetting::SetAndGet<std::string>( [](const std::string& /*value*/) { return false; }, nullptr), &RuntimeOption::BuildId); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_SYSTEM, "notice_frequency", &RuntimeOption::NoticeFrequency); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_SYSTEM, "warning_frequency", &RuntimeOption::WarningFrequency); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_ONLY, "hhvm.build_type", IniSetting::SetAndGet<std::string>( [](const std::string&) { return false; }, []() { return s_hhvm_build_type.c_str(); } )); // Extensions Config::Bind(RuntimeOption::ExtensionDir, ini, config, "extension_dir", RuntimeOption::ExtensionDir, false); Config::Bind(RuntimeOption::DynamicExtensionPath, ini, config, "DynamicExtensionPath", RuntimeOption::DynamicExtensionPath); Config::Bind(RuntimeOption::Extensions, ini, config, "extensions"); Config::Bind(RuntimeOption::DynamicExtensions, ini, config, "DynamicExtensions"); ExtensionRegistry::moduleLoad(ini, config); initialize_apc(); if (TraceFunctions.size()) Trace::ensureInit(getTraceOutputFile()); // arrprov is only for dvarrays. It should be off if HADVAs is on. if (RO::EvalHackArrDVArrs) { RO::EvalArrayProvenance = false; RO::EvalLogArrayProvenance = false; } // Bespoke array-likes // We don't support provenance for bespoke array-likes, so don't construct // any at runtime if we're logging provenance instrumentation results. if (RO::EvalBespokeArrayLikeMode > 0 && (RO::EvalArrayProvenance || RO::EvalLogArrayProvenance)) { RO::EvalBespokeArrayLikeMode = 0; } // If we're going to construct bespoke array-likes at runtime, ensure that // we JIT checks for these types as well. We support JIT-ing these checks // even if there are no runtime bespokes as way to test our guard logic. if (RO::EvalBespokeArrayLikeMode == 0) { specializeVanillaDestructors(); bespoke::setLoggingEnabled(false); } else { bespoke::setLoggingEnabled(true); } // Hack Array Compats if (!RuntimeOption::EvalEmitClsMethPointers) { RuntimeOption::EvalIsCompatibleClsMethType = false; } if (RuntimeOption::EvalArrayProvenance) { RuntimeOption::EvalJitForceVMRegSync = true; } // we need to maintain an invariant that PureEnforceCalls >= RxEnforceCalls... // We can't be stricter on rx than on pure, as that would break rx assumptions RuntimeOption::EvalPureEnforceCalls = std::max( RuntimeOption::EvalPureEnforceCalls, RuntimeOption::EvalRxEnforceCalls); RuntimeOption::EvalPureVerifyBody = std::max( RuntimeOption::EvalPureVerifyBody, RuntimeOption::EvalRxVerifyBody); // Initialize defaults for repo-specific parser configuration options. RepoOptions::setDefaults(config, ini); }
void RuntimeOption::Load( IniSetting::Map& ini, Hdf& config, const std::vector<std::string>& iniClis , const std::vector<std::string>& hdfClis , std::vector<std::string>* messages , std::string cmd ) { ARRPROV_USE_RUNTIME_LOCATION_FORCE(); tl_heap.getCheck(); for (auto& istr : iniClis) { Config::ParseIniString(istr, ini); } for (auto& hstr : hdfClis) { Config::ParseHdfString(hstr, config); } auto m = getTierOverwrites(ini, config); if (messages) *messages = std::move(m); std::string relConfigsError; Config::Bind(s_RelativeConfigs, ini, config, "RelativeConfigs"); if (!cmd.empty() && !s_RelativeConfigs.empty()) { String strcmd(cmd, CopyString); Process::InitProcessStatics(); auto const currentDir = Process::CurrentWorkingDirectory.data(); std::vector<std::string> newConfigs; auto const original = s_RelativeConfigs; for (auto& str : original) { if (str.empty()) continue; std::string fullpath; auto const found = FileUtil::runRelative( str, strcmd, currentDir, [&] (const String& f) { if (access(f.data(), R_OK) == 0) { fullpath = f.toCppString(); FTRACE_MOD(Trace::watchman_autoload, 3, "Parsing {}\n", fullpath); Config::ParseConfigFile(fullpath, ini, config); return true; } return false; } ); if (found) newConfigs.emplace_back(std::move(fullpath)); } if (!newConfigs.empty()) { auto m2 = getTierOverwrites(ini, config); if (messages) *messages = std::move(m2); if (s_RelativeConfigs != original) { relConfigsError = folly::sformat( "RelativeConfigs node was modified while loading configs from [{}] " "to [{}]", folly::join(", ", original), folly::join(", ", s_RelativeConfigs) ); } } s_RelativeConfigs.swap(newConfigs); } else { s_RelativeConfigs.clear(); } for (auto& istr : iniClis) { Config::ParseIniString(istr, ini); } for (auto& hstr : hdfClis) { Config::ParseHdfString(hstr, config); } Config::Bind(PidFile, ini, config, "PidFile", "www.pid"); Config::Bind(DeploymentId, ini, config, "DeploymentId"); { static std::string deploymentIdOverride; Config::Bind(deploymentIdOverride, ini, config, "DeploymentIdOverride"); if (!deploymentIdOverride.empty()) { RuntimeOption::DeploymentId = deploymentIdOverride; } } { Config::Bind(ConfigId, ini, config, "ConfigId", 0); auto configIdCounter = ServiceData::createCounter("vm.config.id"); configIdCounter->setValue(ConfigId); } { auto setLogLevel = [](const std::string& value) { if (value == "None" || value == "") { Logger::LogLevel = Logger::LogNone; } else if (value == "Error") { Logger::LogLevel = Logger::LogError; } else if (value == "Warning") { Logger::LogLevel = Logger::LogWarning; } else if (value == "Info") { Logger::LogLevel = Logger::LogInfo; } else if (value == "Verbose") { Logger::LogLevel = Logger::LogVerbose; } else { return false; } return true; }; auto str = Config::GetString(ini, config, "Log.Level"); if (!str.empty()) { setLogLevel(str); } IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_SYSTEM, "hhvm.log.level", IniSetting::SetAndGet<std::string>( setLogLevel, []() { switch (Logger::LogLevel) { case Logger::LogNone: return "None"; case Logger::LogError: return "Error"; case Logger::LogWarning: return "Warning"; case Logger::LogInfo: return "Info"; case Logger::LogVerbose: return "Verbose"; } return ""; } )); Config::Bind(Logger::UseLogFile, ini, config, "Log.UseLogFile", true); Config::Bind(LogFile, ini, config, "Log.File"); Config::Bind(LogFileSymLink, ini, config, "Log.SymLink"); Config::Bind(LogFilePeriodMultiplier, ini, config, "Log.PeriodMultiplier", 0); if (Logger::UseLogFile && RuntimeOption::ServerExecutionMode()) { RuntimeOption::ErrorLogs[Logger::DEFAULT] = ErrorLogFileData(LogFile, LogFileSymLink, LogFilePeriodMultiplier); } if (Config::GetBool(ini, config, "Log.AlwaysPrintStackTraces")) { Logger::SetTheLogger(Logger::DEFAULT, new ExtendedLogger()); ExtendedLogger::EnabledByDefault = true; } Config::Bind(Logger::LogHeader, ini, config, "Log.Header"); Config::Bind(Logger::LogNativeStackTrace, ini, config, "Log.NativeStackTrace", true); Config::Bind(Logger::UseSyslog, ini, config, "Log.UseSyslog", false); Config::Bind(Logger::UseRequestLog, ini, config, "Log.UseRequestLog", false); Config::Bind(Logger::AlwaysEscapeLog, ini, config, "Log.AlwaysEscapeLog", true); Config::Bind(Logger::UseCronolog, ini, config, "Log.UseCronolog", false); Config::Bind(Logger::MaxMessagesPerRequest, ini, config, "Log.MaxMessagesPerRequest", -1); Config::Bind(LogFileFlusher::DropCacheChunkSize, ini, config, "Log.DropCacheChunkSize", 1 << 20); Config::Bind(RuntimeOption::LogHeaderMangle, ini, config, "Log.HeaderMangle", 0); Config::Bind(AlwaysLogUnhandledExceptions, ini, config, "Log.AlwaysLogUnhandledExceptions", true); Config::Bind(NoSilencer, ini, config, "Log.NoSilencer"); Config::Bind(RuntimeErrorReportingLevel, ini, config, "Log.RuntimeErrorReportingLevel", static_cast<int>(ErrorMode::HPHP_ALL)); Config::Bind(ForceErrorReportingLevel, ini, config, "Log.ForceErrorReportingLevel", 0); Config::Bind(AccessLogDefaultFormat, ini, config, "Log.AccessLogDefaultFormat", "%h %l %u %t \"%r\" %>s %b"); auto parseLogs = [] (const Hdf &config, const IniSetting::Map& ini, const std::string &name, std::map<std::string, AccessLogFileData> &logs) { auto parse_logs_callback = [&] (const IniSetting::Map &ini_pl, const Hdf &hdf_pl, const std::string &ini_pl_key) { string logName = hdf_pl.exists() && !hdf_pl.isEmpty() ? hdf_pl.getName() : ini_pl_key; string fname = Config::GetString(ini_pl, hdf_pl, "File", "", false); if (!fname.empty()) { string symlink = Config::GetString(ini_pl, hdf_pl, "SymLink", "", false); string format = Config::GetString(ini_pl, hdf_pl, "Format", AccessLogDefaultFormat, false); auto periodMultiplier = Config::GetUInt16(ini_pl, hdf_pl, "PeriodMultiplier", 0, false); logs[logName] = AccessLogFileData(fname, symlink, format, periodMultiplier); } }; Config::Iterate(parse_logs_callback, ini, config, name); }; parseLogs(config, ini, "Log.Access", AccessLogs); RPCLogs = AccessLogs; parseLogs(config, ini, "Log.RPC", RPCLogs); Config::Bind(AdminLogFormat, ini, config, "Log.AdminLog.Format", "%h %t %s %U"); Config::Bind(AdminLogFile, ini, config, "Log.AdminLog.File"); Config::Bind(AdminLogSymLink, ini, config, "Log.AdminLog.SymLink"); } { Config::Bind(ErrorUpgradeLevel, ini, config, "ErrorHandling.UpgradeLevel", 0); Config::Bind(MaxSerializedStringSize, ini, config, "ErrorHandling.MaxSerializedStringSize", 64 * 1024 * 1024); Config::Bind(CallUserHandlerOnFatals, ini, config, "ErrorHandling.CallUserHandlerOnFatals", false); Config::Bind(ThrowExceptionOnBadMethodCall, ini, config, "ErrorHandling.ThrowExceptionOnBadMethodCall", true); Config::Bind(LogNativeStackOnOOM, ini, config, "ErrorHandling.LogNativeStackOnOOM", false); Config::Bind(NoInfiniteRecursionDetection, ini, config, "ErrorHandling.NoInfiniteRecursionDetection"); Config::Bind(NoticeFrequency, ini, config, "ErrorHandling.NoticeFrequency", 1); Config::Bind(WarningFrequency, ini, config, "ErrorHandling.WarningFrequency", 1); } if (!relConfigsError.empty()) Logger::Error(relConfigsError); { if (Config::GetInt64(ini, config, "ResourceLimit.CoreFileSizeOverride")) { setResourceLimit(RLIMIT_CORE, ini, config, "ResourceLimit.CoreFileSizeOverride"); } else { setResourceLimit(RLIMIT_CORE, ini, config, "ResourceLimit.CoreFileSize"); } setResourceLimit(RLIMIT_NOFILE, ini, config, "ResourceLimit.MaxSocket"); setResourceLimit(RLIMIT_DATA, ini, config, "ResourceLimit.RSS"); static int64_t s_core_file_size_override, s_core_file_size, s_rss = 0; static int32_t s_max_socket = 0; Config::Bind(s_core_file_size_override, ini, config, "ResourceLimit.CoreFileSizeOverride", 0); Config::Bind(s_core_file_size, ini, config, "ResourceLimit.CoreFileSize", 0); Config::Bind(s_max_socket, ini, config, "ResourceLimit.MaxSocket", 0); Config::Bind(s_rss, ini, config, "ResourceLimit.RSS", 0); Config::Bind(SocketDefaultTimeout, ini, config, "ResourceLimit.SocketDefaultTimeout", 60); Config::Bind(MaxSQLRowCount, ini, config, "ResourceLimit.MaxSQLRowCount", 0); Config::Bind(SerializationSizeLimit, ini, config, "ResourceLimit.SerializationSizeLimit", StringData::MaxSize); Config::Bind(HeapSizeMB, ini, config, "ResourceLimit.HeapSizeMB", HeapSizeMB); Config::Bind(HeapResetCountBase, ini, config, "ResourceLimit.HeapResetCountBase", HeapResetCountBase); Config::Bind(HeapResetCountMultiple, ini, config, "ResourceLimit.HeapResetCountMultiple", HeapResetCountMultiple); Config::Bind(HeapLowWaterMark , ini, config, "ResourceLimit.HeapLowWaterMark", HeapLowWaterMark); Config::Bind(HeapHighWaterMark , ini, config, "ResourceLimit.HeapHighWaterMark",HeapHighWaterMark); } { Config::Bind(DisableCallUserFunc, ini, config, "Hack.Lang.Phpism.DisableCallUserFunc", DisableCallUserFunc); Config::Bind(DisableCallUserFuncArray, ini, config, "Hack.Lang.Phpism.DisableCallUserFuncArray", DisableCallUserFuncArray); Config::Bind(DisableAssert, ini, config, "Hack.Lang.Phpism.DisableAssert", DisableAssert); Config::Bind(DisableNontoplevelDeclarations, ini, config, "Hack.Lang.Phpism.DisableNontoplevelDeclarations", DisableNontoplevelDeclarations); Config::Bind(DisableStaticClosures, ini, config, "Hack.Lang.Phpism.DisableStaticClosures", DisableStaticClosures); Config::Bind(DisableConstant, ini, config, "Hack.Lang.Phpism.DisableConstant", DisableConstant); } { auto repoModeToStr = [](RepoMode mode) { switch (mode) { case RepoMode::Closed: return "--"; case RepoMode::ReadOnly: return "r-"; case RepoMode::ReadWrite: return "rw"; } always_assert(false); return ""; }; auto parseRepoMode = [&](const std::string& repoModeStr, const char* type, RepoMode defaultMode) { if (repoModeStr.empty()) { return defaultMode; } if (repoModeStr == "--") { return RepoMode::Closed; } if (repoModeStr == "r-") { return RepoMode::ReadOnly; } if (repoModeStr == "rw") { return RepoMode::ReadWrite; } Logger::Error("Bad config setting: Repo.%s.Mode=%s", type, repoModeStr.c_str()); return RepoMode::ReadWrite; }; static std::string repoLocalMode; Config::Bind(repoLocalMode, ini, config, "Repo.Local.Mode", repoModeToStr(RepoLocalMode)); RepoLocalMode = parseRepoMode(repoLocalMode, "Local", RepoMode::ReadOnly); Config::Bind(RepoLocalPath, ini, config, "Repo.Local.Path"); if (RepoLocalPath.empty()) { const char* HHVM_REPO_LOCAL_PATH = getenv("HHVM_REPO_LOCAL_PATH"); if (HHVM_REPO_LOCAL_PATH != nullptr) { RepoLocalPath = HHVM_REPO_LOCAL_PATH; } } static std::string repoCentralMode; Config::Bind(repoCentralMode, ini, config, "Repo.Central.Mode", repoModeToStr(RepoCentralMode)); RepoCentralMode = parseRepoMode(repoCentralMode, "Central", RepoMode::ReadWrite); Config::Bind(RepoCentralPath, ini, config, "Repo.Central.Path"); Config::Bind(RepoCentralFileMode, ini, config, "Repo.Central.FileMode"); Config::Bind(RepoCentralFileUser, ini, config, "Repo.Central.FileUser"); Config::Bind(RepoCentralFileGroup, ini, config, "Repo.Central.FileGroup"); Config::Bind(RepoAllowFallbackPath, ini, config, "Repo.AllowFallbackPath", RepoAllowFallbackPath); replacePlaceholders(RepoLocalPath); replacePlaceholders(RepoCentralPath); Config::Bind(RepoJournal, ini, config, "Repo.Journal", RepoJournal); Config::Bind(RepoCommit, ini, config, "Repo.Commit", RepoCommit); Config::Bind(RepoDebugInfo, ini, config, "Repo.DebugInfo", RepoDebugInfo); Config::Bind(RepoLitstrLazyLoad, ini, config, "Repo.LitstrLazyLoad", RepoLitstrLazyLoad); Config::Bind(RepoAuthoritative, ini, config, "Repo.Authoritative", RepoAuthoritative); Config::Bind(RepoLocalReadaheadRate, ini, config, "Repo.LocalReadaheadRate", 0); Config::Bind(RepoLocalReadaheadConcurrent, ini, config, "Repo.LocalReadaheadConcurrent", false); Config::Bind(RepoBusyTimeoutMS, ini, config, "Repo.BusyTimeoutMS", RepoBusyTimeoutMS); } if (use_jemalloc) { Config::Bind(HHProfEnabled, ini, config, "HHProf.Enabled", false); Config::Bind(HHProfActive, ini, config, "HHProf.Active", false); Config::Bind(HHProfAccum, ini, config, "HHProf.Accum", false); Config::Bind(HHProfRequest, ini, config, "HHProf.Request", false); } { Config::Bind(EnableHipHopSyntax, ini, config, "Eval.EnableHipHopSyntax", EnableHipHopSyntax); Config::Bind(EnableShortTags, ini, config, "Eval.EnableShortTags", true); Config::Bind(EnableXHP, ini, config, "Eval.EnableXHP", EnableXHP); Config::Bind(TimeoutsUseWallTime, ini, config, "Eval.TimeoutsUseWallTime", true); Config::Bind(CheckFlushOnUserClose, ini, config, "Eval.CheckFlushOnUserClose", true); Config::Bind(EvalInitialNamedEntityTableSize, ini, config, "Eval.InitialNamedEntityTableSize", EvalInitialNamedEntityTableSize); Config::Bind(EvalInitialStaticStringTableSize, ini, config, "Eval.InitialStaticStringTableSize", EvalInitialStaticStringTableSize); static std::string jitSerdesMode; Config::Bind(jitSerdesMode, ini, config, "Eval.JitSerdesMode", "Off"); EvalJitSerdesMode = [&] { #define X(x) if (jitSerdesMode == #x) return JitSerdesMode::x X(Serialize); X(SerializeAndExit); X(Deserialize); X(DeserializeOrFail); X(DeserializeOrGenerate); X(DeserializeAndDelete); X(DeserializeAndExit); #undef X return JitSerdesMode::Off; }(); Config::Bind(EvalJitSerdesFile, ini, config, "Eval.JitSerdesFile", EvalJitSerdesFile); auto const couldDump = !EvalJitSerdesFile.empty() && (isJitSerializing() || (EvalJitSerdesMode == JitSerdesMode::DeserializeOrGenerate)); Config::Bind(DumpPreciseProfData, ini, config, "Eval.DumpPreciseProfData", couldDump); Config::Bind(ProfDataTTLHours, ini, config, "Eval.ProfDataTTLHours", ProfDataTTLHours); Config::Bind(ProfDataTag, ini, config, "Eval.ProfDataTag", ProfDataTag); Config::Bind(CheckSymLink, ini, config, "Eval.CheckSymLink", true); Config::Bind(TrustAutoloaderPath, ini, config, "Eval.TrustAutoloaderPath", false); #define F(type, name, defaultVal) \ Config::Bind(Eval ## name, ini, config, "Eval."#name, defaultVal); EVALFLAGS() #undef F if (EvalJitSerdesModeForceOff) EvalJitSerdesMode = JitSerdesMode::Off; if (!EvalEnableReusableTC) EvalReusableTCPadding = 0; if (numa_num_nodes <= 1) { EvalEnableNuma = false; } Config::Bind(ServerForkEnabled, ini, config, "Server.Forking.Enabled", ServerForkEnabled); Config::Bind(ServerForkLogging, ini, config, "Server.Forking.LogForkAttempts", ServerForkLogging); if (!ServerForkEnabled && ServerExecutionMode()) { low_2m_pages(EvalMaxLowMemHugePages); high_2m_pages(EvalMaxHighArenaHugePages); } s_enable_static_arena = Config::GetBool(ini, config, "Eval.UseTLStaticArena", true); replacePlaceholders(EvalHackCompilerExtractPath); replacePlaceholders(EvalHackCompilerFallbackPath); replacePlaceholders(EvalEmbeddedDataExtractPath); replacePlaceholders(EvalEmbeddedDataFallbackPath); if (!jit::mcgen::retranslateAllEnabled()) { EvalJitWorkerThreads = 0; if (EvalJitSerdesMode != JitSerdesMode::Off) { if (ServerMode) { Logger::Warning("Eval.JitSerdesMode reset from " + jitSerdesMode + " to off, becasue JitRetranslateAll isn't enabled."); } EvalJitSerdesMode = JitSerdesMode::Off; } EvalJitSerdesFile.clear(); DumpPreciseProfData = false; } EvalJitPGOUseAddrCountedCheck &= addr_encodes_persistency; HardwareCounter::Init(EvalProfileHWEnable, url_decode(EvalProfileHWEvents.data(), EvalProfileHWEvents.size()).toCppString(), false, EvalProfileHWExcludeKernel, EvalProfileHWFastReads, EvalProfileHWExportInterval); Config::Bind(EnableIntrinsicsExtension, ini, config, "Eval.EnableIntrinsicsExtension", EnableIntrinsicsExtension); Config::Bind(RecordCodeCoverage, ini, config, "Eval.RecordCodeCoverage"); if (EvalJit && RecordCodeCoverage) { throw std::runtime_error("Code coverage is not supported with " "Eval.Jit=true"); } Config::Bind(DisableSmallAllocator, ini, config, "Eval.DisableSmallAllocator", DisableSmallAllocator); SetArenaSlabAllocBypass(DisableSmallAllocator); EvalSlabAllocAlign = folly::nextPowTwo(EvalSlabAllocAlign); EvalSlabAllocAlign = std::min(EvalSlabAllocAlign, decltype(EvalSlabAllocAlign){4096}); if (RecordCodeCoverage) CheckSymLink = true; Config::Bind(CodeCoverageOutputFile, ini, config, "Eval.CodeCoverageOutputFile"); Config::Bind(EnableArgsInBacktraces, ini, config, "Eval.EnableArgsInBacktraces", !RepoAuthoritative); Config::Bind(EvalAuthoritativeMode, ini, config, "Eval.AuthoritativeMode", false); Config::Bind(CheckCLIClientCommands, ini, config, "Eval.CheckCLIClientCommands", 1); if (RepoAuthoritative) { EvalAuthoritativeMode = true; } { Config::Bind(EnableHphpdDebugger, ini, config, "Eval.Debugger.EnableDebugger"); Config::Bind(EnableDebuggerColor, ini, config, "Eval.Debugger.EnableDebuggerColor", true); Config::Bind(EnableDebuggerPrompt, ini, config, "Eval.Debugger.EnableDebuggerPrompt", true); Config::Bind(EnableDebuggerServer, ini, config, "Eval.Debugger.EnableDebuggerServer"); Config::Bind(EnableDebuggerUsageLog, ini, config, "Eval.Debugger.EnableDebuggerUsageLog"); Config::Bind(DebuggerServerIP, ini, config, "Eval.Debugger.IP"); Config::Bind(DebuggerServerPort, ini, config, "Eval.Debugger.Port", 8089); Config::Bind(DebuggerDisableIPv6, ini, config, "Eval.Debugger.DisableIPv6", false); Config::Bind(DebuggerDefaultSandboxPath, ini, config, "Eval.Debugger.DefaultSandboxPath"); Config::Bind(DebuggerStartupDocument, ini, config, "Eval.Debugger.StartupDocument"); Config::Bind(DebuggerSignalTimeout, ini, config, "Eval.Debugger.SignalTimeout", 1); Config::Bind(DebuggerDefaultRpcPort, ini, config, "Eval.Debugger.RPC.DefaultPort", 8083); DebuggerDefaultRpcAuth = Config::GetString(ini, config, "Eval.Debugger.RPC.DefaultAuth"); Config::Bind(DebuggerRpcHostDomain, ini, config, "Eval.Debugger.RPC.HostDomain"); Config::Bind(DebuggerDefaultRpcTimeout, ini, config, "Eval.Debugger.RPC.DefaultTimeout", 30); Config::Bind(DebuggerAuthTokenScriptBin, ini, config, "Eval.Debugger.Auth.TokenScriptBin"); Config::Bind(DebuggerSessionAuthScriptBin, ini, config, "Eval.Debugger.Auth.SessionAuthScriptBin"); } } { using jit::CodeCache; Config::Bind(CodeCache::AHotSize, ini, config, "Eval.JitAHotSize", ahotDefault()); Config::Bind(CodeCache::ASize, ini, config, "Eval.JitASize", 60 << 20); Config::Bind(CodeCache::AProfSize, ini, config, "Eval.JitAProfSize", RuntimeOption::EvalJitPGO ? (64 << 20) : 0); Config::Bind(CodeCache::AColdSize, ini, config, "Eval.JitAColdSize", 24 << 20); Config::Bind(CodeCache::AFrozenSize, ini, config, "Eval.JitAFrozenSize", 40 << 20); Config::Bind(CodeCache::ABytecodeSize, ini, config, "Eval.JitABytecodeSize", 0); Config::Bind(CodeCache::GlobalDataSize, ini, config, "Eval.JitGlobalDataSize", CodeCache::ASize >> 2); Config::Bind(CodeCache::MapTCHuge, ini, config, "Eval.MapTCHuge", hugePagesSoundNice()); Config::Bind(CodeCache::TCNumHugeHotMB, ini, config, "Eval.TCNumHugeHotMB", 64); Config::Bind(CodeCache::TCNumHugeMainMB, ini, config, "Eval.TCNumHugeMainMB", 16); Config::Bind(CodeCache::TCNumHugeColdMB, ini, config, "Eval.TCNumHugeColdMB", 4); Config::Bind(CodeCache::AutoTCShift, ini, config, "Eval.JitAutoTCShift", 1); } { Config::Bind(CheckIntOverflow, ini, config, "Hack.Lang.CheckIntOverflow", 0); Config::Bind(StrictArrayFillKeys, ini, config, "Hack.Lang.StrictArrayFillKeys", HackStrictOption::ON); Config::Bind(LookForTypechecker, ini, config, "Hack.Lang.LookForTypechecker", false); Config::Bind(AutoTypecheck, ini, config, "Hack.Lang.AutoTypecheck", LookForTypechecker); Config::Bind(EnableClassLevelWhereClauses, ini, config, "Hack.Lang.EnableClassLevelWhereClauses", false); } { Config::Bind(s_PHP7_master, ini, config, "PHP7.all", s_PHP7_default); Config::Bind(PHP7_EngineExceptions, ini, config, "PHP7.EngineExceptions", s_PHP7_master); Config::Bind(PHP7_NoHexNumerics, ini, config, "PHP7.NoHexNumerics", s_PHP7_master); Config::Bind(PHP7_Builtins, ini, config, "PHP7.Builtins", s_PHP7_master); Config::Bind(PHP7_Substr, ini, config, "PHP7.Substr", s_PHP7_master); Config::Bind(PHP7_DisallowUnsafeCurlUploads, ini, config, "PHP7.DisallowUnsafeCurlUploads", s_PHP7_master); } { Config::Bind(Host, ini, config, "Server.Host"); Config::Bind(DefaultServerNameSuffix, ini, config, "Server.DefaultServerNameSuffix"); Config::Bind(AlwaysDecodePostDataDefault, ini, config, "Server.AlwaysDecodePostDataDefault", AlwaysDecodePostDataDefault); Config::Bind(ServerType, ini, config, "Server.Type", ServerType); Config::Bind(ServerIP, ini, config, "Server.IP"); Config::Bind(ServerFileSocket, ini, config, "Server.FileSocket"); #ifdef FACEBOOK if (GetServerPrimaryIPv4().empty() && GetServerPrimaryIPv6().empty()) { throw std::runtime_error("Unable to resolve the server's " "IPv4 or IPv6 address"); } #endif Config::Bind(ServerPort, ini, config, "Server.Port", 80); Config::Bind(ServerBacklog, ini, config, "Server.Backlog", 128); Config::Bind(ServerConnectionLimit, ini, config, "Server.ConnectionLimit", 0); Config::Bind(ServerThreadCount, ini, config, "Server.ThreadCount", Process::GetCPUCount() * 2); Config::Bind(ServerQueueCount, ini, config, "Server.QueueCount", ServerThreadCount); Config::Bind(ServerIOThreadCount, ini, config, "Server.IOThreadCount", 1); Config::Bind(ServerLegacyBehavior, ini, config, "Server.LegacyBehavior", ServerLegacyBehavior); Config::Bind(ServerHugeThreadCount, ini, config, "Server.HugeThreadCount", 0); Config::Bind(ServerHugeStackKb, ini, config, "Server.HugeStackSizeKb", 384); Config::Bind(ServerLoopSampleRate, ini, config, "Server.LoopSampleRate", 0); Config::Bind(ServerWarmupThrottleRequestCount, ini, config, "Server.WarmupThrottleRequestCount", ServerWarmupThrottleRequestCount); Config::Bind(ServerWarmupThrottleThreadCount, ini, config, "Server.WarmupThrottleThreadCount", Process::GetCPUCount()); Config::Bind(ServerThreadDropCacheTimeoutSeconds, ini, config, "Server.ThreadDropCacheTimeoutSeconds", 0); if (Config::GetBool(ini, config, "Server.ThreadJobLIFO")) { ServerThreadJobLIFOSwitchThreshold = 0; } Config::Bind(ServerThreadJobLIFOSwitchThreshold, ini, config, "Server.ThreadJobLIFOSwitchThreshold", ServerThreadJobLIFOSwitchThreshold); Config::Bind(ServerThreadJobMaxQueuingMilliSeconds, ini, config, "Server.ThreadJobMaxQueuingMilliSeconds", -1); Config::Bind(ServerThreadDropStack, ini, config, "Server.ThreadDropStack"); Config::Bind(ServerHttpSafeMode, ini, config, "Server.HttpSafeMode"); Config::Bind(ServerStatCache, ini, config, "Server.StatCache", false); Config::Bind(ServerFixPathInfo, ini, config, "Server.FixPathInfo", false); Config::Bind(ServerAddVaryEncoding, ini, config, "Server.AddVaryEncoding", ServerAddVaryEncoding); Config::Bind(ServerLogSettingsOnStartup, ini, config, "Server.LogSettingsOnStartup", false); Config::Bind(ServerLogReorderProps, ini, config, "Server.LogReorderProps", false); Config::Bind(ServerWarmupConcurrently, ini, config, "Server.WarmupConcurrently", false); Config::Bind(ServerDedupeWarmupRequests, ini, config, "Server.DedupeWarmupRequests", false); Config::Bind(ServerWarmupThreadCount, ini, config, "Server.WarmupThreadCount", ServerWarmupThreadCount); Config::Bind(ServerExtendedWarmupThreadCount, ini, config, "Server.ExtendedWarmup.ThreadCount", ServerExtendedWarmupThreadCount); Config::Bind(ServerExtendedWarmupDelaySeconds, ini, config, "Server.ExtendedWarmup.DelaySeconds", ServerExtendedWarmupDelaySeconds); Config::Bind(ServerExtendedWarmupRepeat, ini, config, "Server.ExtendedWarmup.Repeat", ServerExtendedWarmupRepeat); Config::Bind(ServerWarmupRequests, ini, config, "Server.WarmupRequests"); Config::Bind(ServerExtendedWarmupRequests, ini, config, "Server.ExtendedWarmup.Requests"); Config::Bind(ServerCleanupRequest, ini, config, "Server.CleanupRequest"); Config::Bind(ServerInternalWarmupThreads, ini, config, "Server.InternalWarmupThreads", 0); Config::Bind(ServerHighPriorityEndPoints, ini, config, "Server.HighPriorityEndPoints"); Config::Bind(ServerExitOnBindFail, ini, config, "Server.ExitOnBindFail", false); Config::Bind(RequestTimeoutSeconds, ini, config, "Server.RequestTimeoutSeconds", 0); Config::Bind(MaxRequestAgeFactor, ini, config, "Server.MaxRequestAgeFactor", 0); Config::Bind(PspTimeoutSeconds, ini, config, "Server.PspTimeoutSeconds", 0); Config::Bind(PspCpuTimeoutSeconds, ini, config, "Server.PspCpuTimeoutSeconds", 0); Config::Bind(RequestMemoryMaxBytes, ini, config, "Server.RequestMemoryMaxBytes", (16LL << 30)); RequestInfo::setOOMKillThreshold( Config::GetUInt64(ini, config, "Server.RequestMemoryOOMKillBytes", 128ULL << 20)); Config::Bind(RequestHugeMaxBytes, ini, config, "Server.RequestHugeMaxBytes", (24LL << 20)); Config::Bind(ServerGracefulShutdownWait, ini, config, "Server.GracefulShutdownWait", 0); Config::Bind(ServerHarshShutdown, ini, config, "Server.HarshShutdown", true); Config::Bind(ServerKillOnTimeout, ini, config, "Server.KillOnTimeout", true); Config::Bind(ServerEvilShutdown, ini, config, "Server.EvilShutdown", true); Config::Bind(ServerPreShutdownWait, ini, config, "Server.PreShutdownWait", 0); Config::Bind(ServerShutdownListenWait, ini, config, "Server.ShutdownListenWait", 0); Config::Bind(ServerShutdownEOMWait, ini, config, "Server.ShutdownEOMWait", 0); Config::Bind(ServerPrepareToStopTimeout, ini, config, "Server.PrepareToStopTimeout", 240); Config::Bind(ServerPartialPostStatusCode, ini, config, "Server.PartialPostStatusCode", -1); Config::Bind(StopOldServer, ini, config, "Server.StopOld", false); Config::Bind(OldServerWait, ini, config, "Server.StopOldWait", 30); Config::Bind(ServerRSSNeededMb, ini, config, "Server.RSSNeededMb", 4096); Config::Bind(ServerCriticalFreeMb, ini, config, "Server.CriticalFreeMb", 512); Config::Bind(CacheFreeFactor, ini, config, "Server.CacheFreeFactor", 50); if (CacheFreeFactor > 100) CacheFreeFactor = 100; if (CacheFreeFactor < 0) CacheFreeFactor = 0; Config::Bind(ServerNextProtocols, ini, config, "Server.SSLNextProtocols"); Config::Bind(ServerEnableH2C, ini, config, "Server.EnableH2C"); extern bool g_brotliUseLocalArena; Config::Bind(g_brotliUseLocalArena, ini, config, "Server.BrotliUseLocalArena", g_brotliUseLocalArena); Config::Bind(BrotliCompressionEnabled, ini, config, "Server.BrotliCompressionEnabled", -1); Config::Bind(BrotliChunkedCompressionEnabled, ini, config, "Server.BrotliChunkedCompressionEnabled", -1); Config::Bind(BrotliCompressionLgWindowSize, ini, config, "Server.BrotliCompressionLgWindowSize", 20); Config::Bind(BrotliCompressionMode, ini, config, "Server.BrotliCompressionMode", 0); Config::Bind(BrotliCompressionQuality, ini, config, "Server.BrotliCompressionQuality", 6); Config::Bind(ZstdCompressionEnabled, ini, config, "Server.ZstdCompressionEnabled", -1); Config::Bind(ZstdCompressor::s_useLocalArena, ini, config, "Server.ZstdUseLocalArena", ZstdCompressor::s_useLocalArena); Config::Bind(ZstdCompressionLevel, ini, config, "Server.ZstdCompressionLevel", 3); Config::Bind(ZstdChecksumRate, ini, config, "Server.ZstdChecksumRate", 0); Config::Bind(GzipCompressionLevel, ini, config, "Server.GzipCompressionLevel", 3); Config::Bind(GzipMaxCompressionLevel, ini, config, "Server.GzipMaxCompressionLevel", 9); Config::Bind(GzipCompressor::s_useLocalArena, ini, config, "Server.GzipUseLocalArena", GzipCompressor::s_useLocalArena); Config::Bind(EnableKeepAlive, ini, config, "Server.EnableKeepAlive", true); Config::Bind(ExposeHPHP, ini, config, "Server.ExposeHPHP", true); Config::Bind(ExposeXFBServer, ini, config, "Server.ExposeXFBServer", false); Config::Bind(ExposeXFBDebug, ini, config, "Server.ExposeXFBDebug", false); Config::Bind(XFBDebugSSLKey, ini, config, "Server.XFBDebugSSLKey", ""); Config::Bind(ConnectionTimeoutSeconds, ini, config, "Server.ConnectionTimeoutSeconds", -1); Config::Bind(EnableOutputBuffering, ini, config, "Server.EnableOutputBuffering"); Config::Bind(OutputHandler, ini, config, "Server.OutputHandler"); Config::Bind(ImplicitFlush, ini, config, "Server.ImplicitFlush"); Config::Bind(EnableEarlyFlush, ini, config, "Server.EnableEarlyFlush", true); Config::Bind(ForceChunkedEncoding, ini, config, "Server.ForceChunkedEncoding"); Config::Bind(MaxPostSize, ini, config, "Server.MaxPostSize", 100); MaxPostSize <<= 20; Config::Bind(AlwaysPopulateRawPostData, ini, config, "Server.AlwaysPopulateRawPostData", false); Config::Bind(TakeoverFilename, ini, config, "Server.TakeoverFilename"); Config::Bind(ExpiresActive, ini, config, "Server.ExpiresActive", true); Config::Bind(ExpiresDefault, ini, config, "Server.ExpiresDefault", 2592000); if (ExpiresDefault < 0) ExpiresDefault = 2592000; Config::Bind(DefaultCharsetName, ini, config, "Server.DefaultCharsetName", ""); Config::Bind(RequestBodyReadLimit, ini, config, "Server.RequestBodyReadLimit", -1); Config::Bind(EnableSSL, ini, config, "Server.EnableSSL"); Config::Bind(SSLPort, ini, config, "Server.SSLPort", 443); Config::Bind(SSLCertificateFile, ini, config, "Server.SSLCertificateFile"); Config::Bind(SSLCertificateKeyFile, ini, config, "Server.SSLCertificateKeyFile"); Config::Bind(SSLCertificateDir, ini, config, "Server.SSLCertificateDir"); Config::Bind(SSLTicketSeedFile, ini, config, "Server.SSLTicketSeedFile"); Config::Bind(TLSDisableTLS1_2, ini, config, "Server.TLSDisableTLS1_2", false); Config::Bind(TLSClientCipherSpec, ini, config, "Server.TLSClientCipherSpec"); Config::Bind(EnableSSLWithPlainText, ini, config, "Server.EnableSSLWithPlainText"); Config::Bind(SSLClientAuthLevel, ini, config, "Server.SSLClientAuthLevel", 0); if (SSLClientAuthLevel < 0) SSLClientAuthLevel = 0; if (SSLClientAuthLevel > 2) SSLClientAuthLevel = 2; Config::Bind(SSLClientCAFile, ini, config, "Server.SSLClientCAFile", ""); if (!SSLClientAuthLevel) { SSLClientCAFile = ""; } else if (SSLClientCAFile.empty()) { throw std::runtime_error( "SSLClientCAFile is required to enable client auth"); } Config::Bind(ClientAuthAclIdentity, ini, config, "Server.ClientAuthAclIdentity", ""); Config::Bind(ClientAuthAclAction, ini, config, "Server.ClientAuthAclAction", ""); Config::Bind(ClientAuthFailClose, ini, config, "Server.ClientAuthFailClose", false); Config::Bind(ClientAuthLogSampleBase, ini, config, "Server.ClientAuthLogSampleBase", 100); if (ClientAuthLogSampleBase < 1) { ClientAuthLogSampleBase = 1; } Config::Bind(SSLClientAuthLoggingSampleRatio, ini, config, "Server.SSLClientAuthLoggingSampleRatio", 0); if (SSLClientAuthLoggingSampleRatio < 0) { SSLClientAuthLoggingSampleRatio = 0; } if (SSLClientAuthLoggingSampleRatio > ClientAuthLogSampleBase) { SSLClientAuthLoggingSampleRatio = ClientAuthLogSampleBase; } Config::Bind(ClientAuthSuccessLogSampleRatio, ini, config, "Server.ClientAuthSuccessLogSampleRatio", 0); if (ClientAuthSuccessLogSampleRatio < SSLClientAuthLoggingSampleRatio) { ClientAuthSuccessLogSampleRatio = SSLClientAuthLoggingSampleRatio; } if (ClientAuthSuccessLogSampleRatio > ClientAuthLogSampleBase) { ClientAuthSuccessLogSampleRatio = ClientAuthLogSampleBase; } Config::Bind(ClientAuthFailureLogSampleRatio, ini, config, "Server.ClientAuthFailureLogSampleRatio", 0); if (ClientAuthFailureLogSampleRatio < SSLClientAuthLoggingSampleRatio) { ClientAuthFailureLogSampleRatio = SSLClientAuthLoggingSampleRatio; } if (ClientAuthFailureLogSampleRatio > ClientAuthLogSampleBase) { ClientAuthFailureLogSampleRatio = ClientAuthLogSampleBase; } auto defSourceRoot = SourceRoot; Config::Bind(SourceRoot, ini, config, "Server.SourceRoot", SourceRoot); SourceRoot = FileUtil::normalizeDir(SourceRoot); if (SourceRoot.empty()) { SourceRoot = defSourceRoot; } FileCache::SourceRoot = SourceRoot; Config::Bind(IncludeSearchPaths, ini, config, "Server.IncludeSearchPaths"); for (unsigned int i = 0; i < IncludeSearchPaths.size(); i++) { IncludeSearchPaths[i] = FileUtil::normalizeDir(IncludeSearchPaths[i]); } IncludeSearchPaths.insert(IncludeSearchPaths.begin(), "."); Config::Bind(AutoloadEnabled, ini, config, "Autoload.Enabled", false); Config::Bind(AutoloadDBPath, ini, config, "Autoload.DBPath"); Config::Bind(FileCache, ini, config, "Server.FileCache"); Config::Bind(DefaultDocument, ini, config, "Server.DefaultDocument", "index.php"); Config::Bind(GlobalDocument, ini, config, "Server.GlobalDocument"); Config::Bind(ErrorDocument404, ini, config, "Server.ErrorDocument404"); normalizePath(ErrorDocument404); Config::Bind(ForbiddenAs404, ini, config, "Server.ForbiddenAs404"); Config::Bind(ErrorDocument500, ini, config, "Server.ErrorDocument500"); normalizePath(ErrorDocument500); Config::Bind(FatalErrorMessage, ini, config, "Server.FatalErrorMessage"); FontPath = FileUtil::normalizeDir( Config::GetString(ini, config, "Server.FontPath")); Config::Bind(EnableStaticContentFromDisk, ini, config, "Server.EnableStaticContentFromDisk", true); Config::Bind(EnableOnDemandUncompress, ini, config, "Server.EnableOnDemandUncompress", true); Config::Bind(EnableStaticContentMMap, ini, config, "Server.EnableStaticContentMMap", true); if (EnableStaticContentMMap) { EnableOnDemandUncompress = true; } Config::Bind(Utf8izeReplace, ini, config, "Server.Utf8izeReplace", true); Config::Bind(RequestInitFunction, ini, config, "Server.RequestInitFunction"); Config::Bind(RequestInitDocument, ini, config, "Server.RequestInitDocument"); Config::Bind(SafeFileAccess, ini, config, "Server.SafeFileAccess"); Config::Bind(AllowedDirectories, ini, config, "Server.AllowedDirectories"); Config::Bind(WhitelistExec, ini, config, "Server.WhitelistExec"); Config::Bind(WhitelistExecWarningOnly, ini, config, "Server.WhitelistExecWarningOnly"); Config::Bind(AllowedExecCmds, ini, config, "Server.AllowedExecCmds"); Config::Bind(UnserializationWhitelistCheck, ini, config, "Server.UnserializationWhitelistCheck", false); Config::Bind(UnserializationWhitelistCheckWarningOnly, ini, config, "Server.UnserializationWhitelistCheckWarningOnly", true); Config::Bind(UnserializationBigMapThreshold, ini, config, "Server.UnserializationBigMapThreshold", 1 << 16); Config::Bind(AllowedFiles, ini, config, "Server.AllowedFiles"); Config::Bind(ForbiddenFileExtensions, ini, config, "Server.ForbiddenFileExtensions"); Config::Bind(LockCodeMemory, ini, config, "Server.LockCodeMemory", false); Config::Bind(MaxArrayChain, ini, config, "Server.MaxArrayChain", INT_MAX); if (MaxArrayChain != INT_MAX) { MaxArrayChain *= 2; } Config::Bind(WarnOnCollectionToArray, ini, config, "Server.WarnOnCollectionToArray", false); Config::Bind(UseDirectCopy, ini, config, "Server.UseDirectCopy", false); Config::Bind(AlwaysUseRelativePath, ini, config, "Server.AlwaysUseRelativePath", false); { Config::Bind(UploadMaxFileSize, ini, config, "Server.Upload.UploadMaxFileSize", 100); UploadMaxFileSize <<= 20; Config::Bind(UploadTmpDir, ini, config, "Server.Upload.UploadTmpDir", "/tmp"); Config::Bind(EnableFileUploads, ini, config, "Server.Upload.EnableFileUploads", true); Config::Bind(MaxFileUploads, ini, config, "Server.Upload.MaxFileUploads", 20); Config::Bind(EnableUploadProgress, ini, config, "Server.Upload.EnableUploadProgress"); Config::Bind(Rfc1867Freq, ini, config, "Server.Upload.Rfc1867Freq", 256 * 1024); if (Rfc1867Freq < 0) Rfc1867Freq = 256 * 1024; Config::Bind(Rfc1867Prefix, ini, config, "Server.Upload.Rfc1867Prefix", "vupload_"); Config::Bind(Rfc1867Name, ini, config, "Server.Upload.Rfc1867Name", "video_ptoken"); } Config::Bind(ImageMemoryMaxBytes, ini, config, "Server.ImageMemoryMaxBytes", 0); if (ImageMemoryMaxBytes == 0) { ImageMemoryMaxBytes = UploadMaxFileSize * 2; } Config::Bind(LightProcessFilePrefix, ini, config, "Server.LightProcessFilePrefix", "./lightprocess"); Config::Bind(LightProcessCount, ini, config, "Server.LightProcessCount", 0); Config::Bind(LightProcess::g_strictUser, ini, config, "Server.LightProcessStrictUser", false); Config::Bind(ForceServerNameToHeader, ini, config, "Server.ForceServerNameToHeader"); Config::Bind(AllowDuplicateCookies, ini, config, "Server.AllowDuplicateCookies", false); Config::Bind(PathDebug, ini, config, "Server.PathDebug", false); Config::Bind(ServerUser, ini, config, "Server.User", ""); Config::Bind(AllowRunAsRoot, ini, config, "Server.AllowRunAsRoot", false); } VirtualHost::SortAllowedDirectories(AllowedDirectories); { auto vh_callback = [] (const IniSettingMap &ini_vh, const Hdf &hdf_vh, const std::string &ini_vh_key) { if (VirtualHost::IsDefault(ini_vh, hdf_vh, ini_vh_key)) { VirtualHost::GetDefault().init(ini_vh, hdf_vh, ini_vh_key); VirtualHost::GetDefault().addAllowedDirectories(AllowedDirectories); } else { auto host = std::make_shared<VirtualHost>(ini_vh, hdf_vh, ini_vh_key); host->addAllowedDirectories(AllowedDirectories); VirtualHosts.push_back(host); } }; Config::Iterate(vh_callback, ini, config, "VirtualHost"); LowestMaxPostSize = VirtualHost::GetLowestMaxPostSize(); } { IpBlocks = std::make_shared<IpBlockMap>(ini, config); } { ReadSatelliteInfo(ini, config, SatelliteServerInfos, XboxPassword, XboxPasswords); } { Config::Bind(XboxServerThreadCount, ini, config, "Xbox.ServerInfo.ThreadCount", 10); Config::Bind(XboxServerMaxQueueLength, ini, config, "Xbox.ServerInfo.MaxQueueLength", INT_MAX); if (XboxServerMaxQueueLength < 0) XboxServerMaxQueueLength = INT_MAX; Config::Bind(XboxServerInfoMaxRequest, ini, config, "Xbox.ServerInfo.MaxRequest", 500); Config::Bind(XboxServerInfoDuration, ini, config, "Xbox.ServerInfo.MaxDuration", 120); Config::Bind(XboxServerInfoReqInitFunc, ini, config, "Xbox.ServerInfo.RequestInitFunction", ""); Config::Bind(XboxServerInfoReqInitDoc, ini, config, "Xbox.ServerInfo.RequestInitDocument", ""); Config::Bind(XboxServerInfoAlwaysReset, ini, config, "Xbox.ServerInfo.AlwaysReset", false); Config::Bind(XboxServerLogInfo, ini, config, "Xbox.ServerInfo.LogInfo", false); Config::Bind(XboxProcessMessageFunc, ini, config, "Xbox.ProcessMessageFunc", "xbox_process_message"); } { Config::Bind(PageletServerThreadCount, ini, config, "PageletServer.ThreadCount", 0); Config::Bind(PageletServerHugeThreadCount, ini, config, "PageletServer.HugeThreadCount", 0); Config::Bind(PageletServerThreadDropStack, ini, config, "PageletServer.ThreadDropStack"); Config::Bind(PageletServerThreadDropCacheTimeoutSeconds, ini, config, "PageletServer.ThreadDropCacheTimeoutSeconds", 0); Config::Bind(PageletServerQueueLimit, ini, config, "PageletServer.QueueLimit", 0); } { hphp_string_imap<std::string> staticFileDefault; staticFileDefault["css"] = "text/css"; staticFileDefault["gif"] = "image/gif"; staticFileDefault["html"] = "text/html"; staticFileDefault["jpeg"] = "image/jpeg"; staticFileDefault["jpg"] = "image/jpeg"; staticFileDefault["mp3"] = "audio/mpeg"; staticFileDefault["png"] = "image/png"; staticFileDefault["tif"] = "image/tiff"; staticFileDefault["tiff"] = "image/tiff"; staticFileDefault["txt"] = "text/plain"; staticFileDefault["zip"] = "application/zip"; Config::Bind(StaticFileExtensions, ini, config, "StaticFile.Extensions", staticFileDefault); auto matches_callback = [](const IniSettingMap& ini_m, const Hdf& hdf_m, const std::string& ) { FilesMatches.push_back(std::make_shared<FilesMatch>(ini_m, hdf_m)); }; Config::Iterate(matches_callback, ini, config, "StaticFile.FilesMatch"); } { Config::Bind(PhpFileExtensions, ini, config, "PhpFile.Extensions"); } { Config::Bind(AdminServerIP, ini, config, "AdminServer.IP", ServerIP); Config::Bind(AdminServerPort, ini, config, "AdminServer.Port", 0); Config::Bind(AdminThreadCount, ini, config, "AdminServer.ThreadCount", 1); Config::Bind(AdminServerEnableSSLWithPlainText, ini, config, "AdminServer.EnableSSLWithPlainText", false); Config::Bind(AdminServerStatsNeedPassword, ini, config, "AdminServer.StatsNeedPassword", AdminServerStatsNeedPassword); AdminPassword = Config::GetString(ini, config, "AdminServer.Password"); AdminPasswords = Config::GetSet(ini, config, "AdminServer.Passwords"); HashedAdminPasswords = Config::GetSet(ini, config, "AdminServer.HashedPasswords"); Config::Bind(AdminDumpPath, ini, config, "AdminServer.DumpPath", "/tmp/hhvm_admin_dump"); } { Config::Bind(ProxyOriginRaw, ini, config, "Proxy.Origin"); Config::Bind(ProxyPercentageRaw, ini, config, "Proxy.Percentage", 0); Config::Bind(ProxyRetry, ini, config, "Proxy.Retry", 3); Config::Bind(UseServeURLs, ini, config, "Proxy.ServeURLs"); Config::Bind(ServeURLs, ini, config, "Proxy.ServeURLs"); Config::Bind(UseProxyURLs, ini, config, "Proxy.ProxyURLs"); Config::Bind(ProxyURLs, ini, config, "Proxy.ProxyURLs"); Config::Bind(ProxyPatterns, ini, config, "Proxy.ProxyPatterns"); } { Config::Bind(HttpDefaultTimeout, ini, config, "Http.DefaultTimeout", 30); Config::Bind(HttpSlowQueryThreshold, ini, config, "Http.SlowQueryThreshold", 5000); } { Config::Bind(NativeStackTrace, ini, config, "Debug.NativeStackTrace"); StackTrace::Enabled = NativeStackTrace; Config::Bind(ServerErrorMessage, ini, config, "Debug.ServerErrorMessage"); Config::Bind(RecordInput, ini, config, "Debug.RecordInput"); Config::Bind(ClearInputOnSuccess, ini, config, "Debug.ClearInputOnSuccess", true); Config::Bind(ProfilerOutputDir, ini, config, "Debug.ProfilerOutputDir", "/tmp"); Config::Bind(CoreDumpEmail, ini, config, "Debug.CoreDumpEmail"); Config::Bind(CoreDumpReport, ini, config, "Debug.CoreDumpReport", true); if (CoreDumpReport) { install_crash_reporter(); } Config::Bind(CoreDumpReportDirectory, ini, config, "Debug.CoreDumpReportDirectory", CoreDumpReportDirectory); std::ostringstream stack_trace_stream; stack_trace_stream << CoreDumpReportDirectory << "/stacktrace." << (int64_t)getpid() << ".log"; StackTraceFilename = stack_trace_stream.str(); Config::Bind(StackTraceTimeout, ini, config, "Debug.StackTraceTimeout", 0); Config::Bind(RemoteTraceOutputDir, ini, config, "Debug.RemoteTraceOutputDir", "/tmp"); Config::Bind(TraceFunctions, ini, config, "Debug.TraceFunctions", TraceFunctions); } { Config::Bind(EnableStats, ini, config, "Stats.Enable", false); Config::Bind(EnableAPCStats, ini, config, "Stats.APC", false); Config::Bind(EnableWebStats, ini, config, "Stats.Web"); Config::Bind(EnableMemoryStats, ini, config, "Stats.Memory"); Config::Bind(EnableSQLStats, ini, config, "Stats.SQL"); Config::Bind(EnableSQLTableStats, ini, config, "Stats.SQLTable"); Config::Bind(EnableNetworkIOStatus, ini, config, "Stats.NetworkIO"); Config::Bind(StatsXSL, ini, config, "Stats.XSL"); Config::Bind(StatsXSLProxy, ini, config, "Stats.XSLProxy"); Config::Bind(StatsSlotDuration, ini, config, "Stats.SlotDuration", 10 * 60); Config::Bind(StatsMaxSlot, ini, config, "Stats.MaxSlot", 12 * 6); StatsSlotDuration = std::max(1u, StatsSlotDuration); StatsMaxSlot = std::max(2u, StatsMaxSlot); Config::Bind(EnableHotProfiler, ini, config, "Stats.EnableHotProfiler", true); Config::Bind(ProfilerTraceBuffer, ini, config, "Stats.ProfilerTraceBuffer", 2000000); Config::Bind(ProfilerTraceExpansion, ini, config, "Stats.ProfilerTraceExpansion", 1.2); Config::Bind(ProfilerMaxTraceBuffer, ini, config, "Stats.ProfilerMaxTraceBuffer", 0); Config::Bind(TrackPerUnitMemory, ini, config, "Stats.TrackPerUnitMemory", false); } { Config::Bind(ServerVariables, ini, config, "ServerVariables"); Config::Bind(EnvVariables, ini, config, "EnvVariables"); } { Config::Bind(SandboxMode, ini, config, "Sandbox.SandboxMode"); Config::Bind(SandboxPattern, ini, config, "Sandbox.Pattern"); SandboxPattern = format_pattern(SandboxPattern, true); Config::Bind(SandboxHome, ini, config, "Sandbox.Home"); Config::Bind(SandboxFallback, ini, config, "Sandbox.Fallback"); Config::Bind(SandboxConfFile, ini, config, "Sandbox.ConfFile"); Config::Bind(SandboxFromCommonRoot, ini, config, "Sandbox.FromCommonRoot"); Config::Bind(SandboxDirectoriesRoot, ini, config, "Sandbox.DirectoriesRoot"); Config::Bind(SandboxLogsRoot, ini, config, "Sandbox.LogsRoot"); Config::Bind(SandboxServerVariables, ini, config, "Sandbox.ServerVariables"); Config::Bind(SandboxDefaultUserFile, ini, config, "Sandbox.DefaultUserFile"); Config::Bind(SandboxHostAlias, ini, config, "Sandbox.HostAlias"); } { Config::Bind(SendmailPath, ini, config, "Mail.SendmailPath", "/usr/lib/sendmail -t -i"); Config::Bind(MailForceExtraParameters, ini, config, "Mail.ForceExtraParameters"); } { Config::Bind(PregBacktraceLimit, ini, config, "Preg.BacktraceLimit", 1000000); Config::Bind(PregRecursionLimit, ini, config, "Preg.RecursionLimit", 100000); Config::Bind(EnablePregErrorLog, ini, config, "Preg.ErrorLog", true); } { Config::Bind(SimpleXMLEmptyNamespaceMatchesAll, ini, config, "SimpleXML.EmptyNamespaceMatchesAll", false); } #ifdef FACEBOOK { Config::Bind(EnableFb303Server, ini, config, "Fb303Server.Enable", EnableFb303Server); Config::Bind(Fb303ServerPort, ini, config, "Fb303Server.Port", 0); Config::Bind(Fb303ServerIP, ini, config, "Fb303Server.IP"); Config::Bind(Fb303ServerThreadStackSizeMb, ini, config, "Fb303Server.ThreadStackSizeMb", 8); Config::Bind(Fb303ServerWorkerThreads, ini, config, "Fb303Server.WorkerThreads", 1); Config::Bind(Fb303ServerPoolThreads, ini, config, "Fb303Server.PoolThreads", 1); } #endif { Config::Bind(XenonPeriodSeconds, ini, config, "Xenon.Period", 0.0); Config::Bind(XenonRequestFreq, ini, config, "Xenon.RequestFreq", 1); Config::Bind(XenonForceAlwaysOn, ini, config, "Xenon.ForceAlwaysOn", false); } { Config::Bind(StrobelightEnabled, ini, config, "Strobelight.Enabled", false); } { Config::Bind(SetProfileNullThisObject, ini, config, "SetProfile.NullThisObject", true); } { Variant v; bool b = IniSetting::GetSystem("zend.assertions", v); if (b) RuntimeOption::AssertEmitted = v.toInt64() >= 0; } Config::Bind(TzdataSearchPaths, ini, config, "TzdataSearchPaths"); Config::Bind(CustomSettings, ini, config, "CustomSettings"); refineStaticStringTableSize(); InitFiniNode::ProcessPostRuntimeOptions(); Config::Bind(EnableZendIniCompat, ini, config, "Eval.EnableZendIniCompat", true); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_ONLY, "expose_php", &RuntimeOption::ExposeHPHP); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_PERDIR, "auto_prepend_file", &RuntimeOption::AutoPrependFile); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_PERDIR, "auto_append_file", &RuntimeOption::AutoAppendFile); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_PERDIR, "post_max_size", IniSetting::SetAndGet<int64_t>( nullptr, []() { return VirtualHost::GetMaxPostSize(); } ), &RuntimeOption::MaxPostSize); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_PERDIR, "always_populate_raw_post_data", &RuntimeOption::AlwaysPopulateRawPostData); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_SYSTEM, "doc_root", &RuntimeOption::SourceRoot); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_SYSTEM, "sendmail_path", &RuntimeOption::SendmailPath); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_ONLY, "pid", &RuntimeOption::PidFile); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_SYSTEM, "file_uploads", "true", &RuntimeOption::EnableFileUploads); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_SYSTEM, "upload_tmp_dir", &RuntimeOption::UploadTmpDir); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_PERDIR, "upload_max_filesize", IniSetting::SetAndGet<std::string>( [](const std::string& value) { return ini_on_update( value, RuntimeOption::UploadMaxFileSize); }, []() { return convert_long_to_bytes( VirtualHost::GetUploadMaxFileSize()); } )); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_SYSTEM, "allow_url_fopen", IniSetting::SetAndGet<std::string>( [](const std::string& ) { return false; }, []() { return "1"; })); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_NONE, "hphp.compiler_id", IniSetting::SetAndGet<std::string>( [](const std::string& ) { return false; }, []() { return compilerId().begin(); })); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_NONE, "hphp.compiler_version", IniSetting::SetAndGet<std::string>( [](const std::string& ) { return false; }, []() { return getHphpCompilerVersion(); })); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_NONE, "hphp.cli_server_api_version", IniSetting::SetAndGet<uint64_t>( [](const uint64_t ) { return false; }, []() { return cli_server_api_version(); })); IniSetting::Bind( IniSetting::CORE, IniSetting::PHP_INI_NONE, "hphp.build_id", IniSetting::SetAndGet<std::string>( [](const std::string& ) { return false; }, nullptr), &RuntimeOption::BuildId); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_SYSTEM, "notice_frequency", &RuntimeOption::NoticeFrequency); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_SYSTEM, "warning_frequency", &RuntimeOption::WarningFrequency); IniSetting::Bind(IniSetting::CORE, IniSetting::PHP_INI_ONLY, "hhvm.build_type", IniSetting::SetAndGet<std::string>( [](const std::string&) { return false; }, []() { return s_hhvm_build_type.c_str(); } )); Config::Bind(RuntimeOption::ExtensionDir, ini, config, "extension_dir", RuntimeOption::ExtensionDir, false); Config::Bind(RuntimeOption::DynamicExtensionPath, ini, config, "DynamicExtensionPath", RuntimeOption::DynamicExtensionPath); Config::Bind(RuntimeOption::Extensions, ini, config, "extensions"); Config::Bind(RuntimeOption::DynamicExtensions, ini, config, "DynamicExtensions"); ExtensionRegistry::moduleLoad(ini, config); initialize_apc(); if (TraceFunctions.size()) Trace::ensureInit(getTraceOutputFile()); if (RO::EvalHackArrDVArrs) { RO::EvalArrayProvenance = false; RO::EvalLogArrayProvenance = false; } if (RO::EvalBespokeArrayLikeMode > 0 && (RO::EvalArrayProvenance || RO::EvalLogArrayProvenance)) { RO::EvalBespokeArrayLikeMode = 0; } if (RO::EvalBespokeArrayLikeMode == 0) { specializeVanillaDestructors(); bespoke::setLoggingEnabled(false); } else { bespoke::setLoggingEnabled(true); } if (!RuntimeOption::EvalEmitClsMethPointers) { RuntimeOption::EvalIsCompatibleClsMethType = false; } if (RuntimeOption::EvalArrayProvenance) { RuntimeOption::EvalJitForceVMRegSync = true; } RuntimeOption::EvalPureEnforceCalls = std::max( RuntimeOption::EvalPureEnforceCalls, RuntimeOption::EvalRxEnforceCalls); RuntimeOption::EvalPureVerifyBody = std::max( RuntimeOption::EvalPureVerifyBody, RuntimeOption::EvalRxVerifyBody); RepoOptions::setDefaults(config, ini); }
1,535
1
__rta_reserve(struct sk_buff *skb, int attrtype, int attrlen) { struct rtattr *rta; int size = RTA_LENGTH(attrlen); rta = (struct rtattr*)skb_put(skb, RTA_ALIGN(size)); rta->rta_type = attrtype; rta->rta_len = size; return rta; }
__rta_reserve(struct sk_buff *skb, int attrtype, int attrlen) { struct rtattr *rta; int size = RTA_LENGTH(attrlen); rta = (struct rtattr*)skb_put(skb, RTA_ALIGN(size)); rta->rta_type = attrtype; rta->rta_len = size; return rta; }
1,537
1
void __rta_fill(struct sk_buff *skb, int attrtype, int attrlen, const void *data) { struct rtattr *rta; int size = RTA_LENGTH(attrlen); rta = (struct rtattr*)skb_put(skb, RTA_ALIGN(size)); rta->rta_type = attrtype; rta->rta_len = size; memcpy(RTA_DATA(rta), data, attrlen); }
void __rta_fill(struct sk_buff *skb, int attrtype, int attrlen, const void *data) { struct rtattr *rta; int size = RTA_LENGTH(attrlen); rta = (struct rtattr*)skb_put(skb, RTA_ALIGN(size)); rta->rta_type = attrtype; rta->rta_len = size; memcpy(RTA_DATA(rta), data, attrlen); }
1,540
0
static void hls_prediction_unit(HEVCContext *s, int x0, int y0, int nPbW, int nPbH, int log2_cb_size, int partIdx) { #define POS(c_idx, x, y) \ &s->frame->data[c_idx][((y) >> s->sps->vshift[c_idx]) * s->frame->linesize[c_idx] + \ (((x) >> s->sps->hshift[c_idx]) << s->sps->pixel_shift)] HEVCLocalContext *lc = &s->HEVClc; int merge_idx = 0; struct MvField current_mv = {{{ 0 }}}; int min_pu_width = s->sps->min_pu_width; MvField *tab_mvf = s->ref->tab_mvf; RefPicList *refPicList = s->ref->refPicList; HEVCFrame *ref0, *ref1; int tmpstride = MAX_PB_SIZE; uint8_t *dst0 = POS(0, x0, y0); uint8_t *dst1 = POS(1, x0, y0); uint8_t *dst2 = POS(2, x0, y0); int log2_min_cb_size = s->sps->log2_min_cb_size; int min_cb_width = s->sps->min_cb_width; int x_cb = x0 >> log2_min_cb_size; int y_cb = y0 >> log2_min_cb_size; int x_pu, y_pu; int i, j; int skip_flag = SAMPLE_CTB(s->skip_flag, x_cb, y_cb); if (!skip_flag) lc->pu.merge_flag = ff_hevc_merge_flag_decode(s); if (skip_flag || lc->pu.merge_flag) { if (s->sh.max_num_merge_cand > 1) merge_idx = ff_hevc_merge_idx_decode(s); else merge_idx = 0; ff_hevc_luma_mv_merge_mode(s, x0, y0, nPbW, nPbH, log2_cb_size, partIdx, merge_idx, &current_mv); } else { enum InterPredIdc inter_pred_idc = PRED_L0; int mvp_flag; ff_hevc_set_neighbour_available(s, x0, y0, nPbW, nPbH); if (s->sh.slice_type == B_SLICE) inter_pred_idc = ff_hevc_inter_pred_idc_decode(s, nPbW, nPbH); if (inter_pred_idc != PRED_L1) { if (s->sh.nb_refs[L0]) { current_mv.ref_idx[0]= ff_hevc_ref_idx_lx_decode(s, s->sh.nb_refs[L0]); } current_mv.pred_flag[0] = 1; hls_mvd_coding(s, x0, y0, 0); mvp_flag = ff_hevc_mvp_lx_flag_decode(s); ff_hevc_luma_mv_mvp_mode(s, x0, y0, nPbW, nPbH, log2_cb_size, partIdx, merge_idx, &current_mv, mvp_flag, 0); current_mv.mv[0].x += lc->pu.mvd.x; current_mv.mv[0].y += lc->pu.mvd.y; } if (inter_pred_idc != PRED_L0) { if (s->sh.nb_refs[L1]) { current_mv.ref_idx[1]= ff_hevc_ref_idx_lx_decode(s, s->sh.nb_refs[L1]); } if (s->sh.mvd_l1_zero_flag == 1 && inter_pred_idc == PRED_BI) { AV_ZERO32(&lc->pu.mvd); } else { hls_mvd_coding(s, x0, y0, 1); } current_mv.pred_flag[1] = 1; mvp_flag = ff_hevc_mvp_lx_flag_decode(s); ff_hevc_luma_mv_mvp_mode(s, x0, y0, nPbW, nPbH, log2_cb_size, partIdx, merge_idx, &current_mv, mvp_flag, 1); current_mv.mv[1].x += lc->pu.mvd.x; current_mv.mv[1].y += lc->pu.mvd.y; } } x_pu = x0 >> s->sps->log2_min_pu_size; y_pu = y0 >> s->sps->log2_min_pu_size; for (j = 0; j < nPbH >> s->sps->log2_min_pu_size; j++) for (i = 0; i < nPbW >> s->sps->log2_min_pu_size; i++) tab_mvf[(y_pu + j) * min_pu_width + x_pu + i] = current_mv; if (current_mv.pred_flag[0]) { ref0 = refPicList[0].ref[current_mv.ref_idx[0]]; if (!ref0) return; hevc_await_progress(s, ref0, &current_mv.mv[0], y0, nPbH); } if (current_mv.pred_flag[1]) { ref1 = refPicList[1].ref[current_mv.ref_idx[1]]; if (!ref1) return; hevc_await_progress(s, ref1, &current_mv.mv[1], y0, nPbH); } if (current_mv.pred_flag[0] && !current_mv.pred_flag[1]) { DECLARE_ALIGNED(16, int16_t, tmp[MAX_PB_SIZE * MAX_PB_SIZE]); DECLARE_ALIGNED(16, int16_t, tmp2[MAX_PB_SIZE * MAX_PB_SIZE]); luma_mc(s, tmp, tmpstride, ref0->frame, &current_mv.mv[0], x0, y0, nPbW, nPbH); if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) || (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) { s->hevcdsp.weighted_pred(s->sh.luma_log2_weight_denom, s->sh.luma_weight_l0[current_mv.ref_idx[0]], s->sh.luma_offset_l0[current_mv.ref_idx[0]], dst0, s->frame->linesize[0], tmp, tmpstride, nPbW, nPbH); } else { s->hevcdsp.put_unweighted_pred(dst0, s->frame->linesize[0], tmp, tmpstride, nPbW, nPbH); } chroma_mc(s, tmp, tmp2, tmpstride, ref0->frame, &current_mv.mv[0], x0 / 2, y0 / 2, nPbW / 2, nPbH / 2); if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) || (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) { s->hevcdsp.weighted_pred(s->sh.chroma_log2_weight_denom, s->sh.chroma_weight_l0[current_mv.ref_idx[0]][0], s->sh.chroma_offset_l0[current_mv.ref_idx[0]][0], dst1, s->frame->linesize[1], tmp, tmpstride, nPbW / 2, nPbH / 2); s->hevcdsp.weighted_pred(s->sh.chroma_log2_weight_denom, s->sh.chroma_weight_l0[current_mv.ref_idx[0]][1], s->sh.chroma_offset_l0[current_mv.ref_idx[0]][1], dst2, s->frame->linesize[2], tmp2, tmpstride, nPbW / 2, nPbH / 2); } else { s->hevcdsp.put_unweighted_pred(dst1, s->frame->linesize[1], tmp, tmpstride, nPbW/2, nPbH/2); s->hevcdsp.put_unweighted_pred(dst2, s->frame->linesize[2], tmp2, tmpstride, nPbW/2, nPbH/2); } } else if (!current_mv.pred_flag[0] && current_mv.pred_flag[1]) { DECLARE_ALIGNED(16, int16_t, tmp [MAX_PB_SIZE * MAX_PB_SIZE]); DECLARE_ALIGNED(16, int16_t, tmp2[MAX_PB_SIZE * MAX_PB_SIZE]); if (!ref1) return; luma_mc(s, tmp, tmpstride, ref1->frame, &current_mv.mv[1], x0, y0, nPbW, nPbH); if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) || (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) { s->hevcdsp.weighted_pred(s->sh.luma_log2_weight_denom, s->sh.luma_weight_l1[current_mv.ref_idx[1]], s->sh.luma_offset_l1[current_mv.ref_idx[1]], dst0, s->frame->linesize[0], tmp, tmpstride, nPbW, nPbH); } else { s->hevcdsp.put_unweighted_pred(dst0, s->frame->linesize[0], tmp, tmpstride, nPbW, nPbH); } chroma_mc(s, tmp, tmp2, tmpstride, ref1->frame, &current_mv.mv[1], x0/2, y0/2, nPbW/2, nPbH/2); if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) || (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) { s->hevcdsp.weighted_pred(s->sh.chroma_log2_weight_denom, s->sh.chroma_weight_l1[current_mv.ref_idx[1]][0], s->sh.chroma_offset_l1[current_mv.ref_idx[1]][0], dst1, s->frame->linesize[1], tmp, tmpstride, nPbW/2, nPbH/2); s->hevcdsp.weighted_pred(s->sh.chroma_log2_weight_denom, s->sh.chroma_weight_l1[current_mv.ref_idx[1]][1], s->sh.chroma_offset_l1[current_mv.ref_idx[1]][1], dst2, s->frame->linesize[2], tmp2, tmpstride, nPbW/2, nPbH/2); } else { s->hevcdsp.put_unweighted_pred(dst1, s->frame->linesize[1], tmp, tmpstride, nPbW/2, nPbH/2); s->hevcdsp.put_unweighted_pred(dst2, s->frame->linesize[2], tmp2, tmpstride, nPbW/2, nPbH/2); } } else if (current_mv.pred_flag[0] && current_mv.pred_flag[1]) { DECLARE_ALIGNED(16, int16_t, tmp [MAX_PB_SIZE * MAX_PB_SIZE]); DECLARE_ALIGNED(16, int16_t, tmp2[MAX_PB_SIZE * MAX_PB_SIZE]); DECLARE_ALIGNED(16, int16_t, tmp3[MAX_PB_SIZE * MAX_PB_SIZE]); DECLARE_ALIGNED(16, int16_t, tmp4[MAX_PB_SIZE * MAX_PB_SIZE]); HEVCFrame *ref0 = refPicList[0].ref[current_mv.ref_idx[0]]; HEVCFrame *ref1 = refPicList[1].ref[current_mv.ref_idx[1]]; if (!ref0 || !ref1) return; luma_mc(s, tmp, tmpstride, ref0->frame, &current_mv.mv[0], x0, y0, nPbW, nPbH); luma_mc(s, tmp2, tmpstride, ref1->frame, &current_mv.mv[1], x0, y0, nPbW, nPbH); if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) || (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) { s->hevcdsp.weighted_pred_avg(s->sh.luma_log2_weight_denom, s->sh.luma_weight_l0[current_mv.ref_idx[0]], s->sh.luma_weight_l1[current_mv.ref_idx[1]], s->sh.luma_offset_l0[current_mv.ref_idx[0]], s->sh.luma_offset_l1[current_mv.ref_idx[1]], dst0, s->frame->linesize[0], tmp, tmp2, tmpstride, nPbW, nPbH); } else { s->hevcdsp.put_weighted_pred_avg(dst0, s->frame->linesize[0], tmp, tmp2, tmpstride, nPbW, nPbH); } chroma_mc(s, tmp, tmp2, tmpstride, ref0->frame, &current_mv.mv[0], x0 / 2, y0 / 2, nPbW / 2, nPbH / 2); chroma_mc(s, tmp3, tmp4, tmpstride, ref1->frame, &current_mv.mv[1], x0 / 2, y0 / 2, nPbW / 2, nPbH / 2); if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) || (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) { s->hevcdsp.weighted_pred_avg(s->sh.chroma_log2_weight_denom, s->sh.chroma_weight_l0[current_mv.ref_idx[0]][0], s->sh.chroma_weight_l1[current_mv.ref_idx[1]][0], s->sh.chroma_offset_l0[current_mv.ref_idx[0]][0], s->sh.chroma_offset_l1[current_mv.ref_idx[1]][0], dst1, s->frame->linesize[1], tmp, tmp3, tmpstride, nPbW / 2, nPbH / 2); s->hevcdsp.weighted_pred_avg(s->sh.chroma_log2_weight_denom, s->sh.chroma_weight_l0[current_mv.ref_idx[0]][1], s->sh.chroma_weight_l1[current_mv.ref_idx[1]][1], s->sh.chroma_offset_l0[current_mv.ref_idx[0]][1], s->sh.chroma_offset_l1[current_mv.ref_idx[1]][1], dst2, s->frame->linesize[2], tmp2, tmp4, tmpstride, nPbW / 2, nPbH / 2); } else { s->hevcdsp.put_weighted_pred_avg(dst1, s->frame->linesize[1], tmp, tmp3, tmpstride, nPbW/2, nPbH/2); s->hevcdsp.put_weighted_pred_avg(dst2, s->frame->linesize[2], tmp2, tmp4, tmpstride, nPbW/2, nPbH/2); } } }
static void hls_prediction_unit(HEVCContext *s, int x0, int y0, int nPbW, int nPbH, int log2_cb_size, int partIdx) { #define POS(c_idx, x, y) \ &s->frame->data[c_idx][((y) >> s->sps->vshift[c_idx]) * s->frame->linesize[c_idx] + \ (((x) >> s->sps->hshift[c_idx]) << s->sps->pixel_shift)] HEVCLocalContext *lc = &s->HEVClc; int merge_idx = 0; struct MvField current_mv = {{{ 0 }}}; int min_pu_width = s->sps->min_pu_width; MvField *tab_mvf = s->ref->tab_mvf; RefPicList *refPicList = s->ref->refPicList; HEVCFrame *ref0, *ref1; int tmpstride = MAX_PB_SIZE; uint8_t *dst0 = POS(0, x0, y0); uint8_t *dst1 = POS(1, x0, y0); uint8_t *dst2 = POS(2, x0, y0); int log2_min_cb_size = s->sps->log2_min_cb_size; int min_cb_width = s->sps->min_cb_width; int x_cb = x0 >> log2_min_cb_size; int y_cb = y0 >> log2_min_cb_size; int x_pu, y_pu; int i, j; int skip_flag = SAMPLE_CTB(s->skip_flag, x_cb, y_cb); if (!skip_flag) lc->pu.merge_flag = ff_hevc_merge_flag_decode(s); if (skip_flag || lc->pu.merge_flag) { if (s->sh.max_num_merge_cand > 1) merge_idx = ff_hevc_merge_idx_decode(s); else merge_idx = 0; ff_hevc_luma_mv_merge_mode(s, x0, y0, nPbW, nPbH, log2_cb_size, partIdx, merge_idx, &current_mv); } else { enum InterPredIdc inter_pred_idc = PRED_L0; int mvp_flag; ff_hevc_set_neighbour_available(s, x0, y0, nPbW, nPbH); if (s->sh.slice_type == B_SLICE) inter_pred_idc = ff_hevc_inter_pred_idc_decode(s, nPbW, nPbH); if (inter_pred_idc != PRED_L1) { if (s->sh.nb_refs[L0]) { current_mv.ref_idx[0]= ff_hevc_ref_idx_lx_decode(s, s->sh.nb_refs[L0]); } current_mv.pred_flag[0] = 1; hls_mvd_coding(s, x0, y0, 0); mvp_flag = ff_hevc_mvp_lx_flag_decode(s); ff_hevc_luma_mv_mvp_mode(s, x0, y0, nPbW, nPbH, log2_cb_size, partIdx, merge_idx, &current_mv, mvp_flag, 0); current_mv.mv[0].x += lc->pu.mvd.x; current_mv.mv[0].y += lc->pu.mvd.y; } if (inter_pred_idc != PRED_L0) { if (s->sh.nb_refs[L1]) { current_mv.ref_idx[1]= ff_hevc_ref_idx_lx_decode(s, s->sh.nb_refs[L1]); } if (s->sh.mvd_l1_zero_flag == 1 && inter_pred_idc == PRED_BI) { AV_ZERO32(&lc->pu.mvd); } else { hls_mvd_coding(s, x0, y0, 1); } current_mv.pred_flag[1] = 1; mvp_flag = ff_hevc_mvp_lx_flag_decode(s); ff_hevc_luma_mv_mvp_mode(s, x0, y0, nPbW, nPbH, log2_cb_size, partIdx, merge_idx, &current_mv, mvp_flag, 1); current_mv.mv[1].x += lc->pu.mvd.x; current_mv.mv[1].y += lc->pu.mvd.y; } } x_pu = x0 >> s->sps->log2_min_pu_size; y_pu = y0 >> s->sps->log2_min_pu_size; for (j = 0; j < nPbH >> s->sps->log2_min_pu_size; j++) for (i = 0; i < nPbW >> s->sps->log2_min_pu_size; i++) tab_mvf[(y_pu + j) * min_pu_width + x_pu + i] = current_mv; if (current_mv.pred_flag[0]) { ref0 = refPicList[0].ref[current_mv.ref_idx[0]]; if (!ref0) return; hevc_await_progress(s, ref0, &current_mv.mv[0], y0, nPbH); } if (current_mv.pred_flag[1]) { ref1 = refPicList[1].ref[current_mv.ref_idx[1]]; if (!ref1) return; hevc_await_progress(s, ref1, &current_mv.mv[1], y0, nPbH); } if (current_mv.pred_flag[0] && !current_mv.pred_flag[1]) { DECLARE_ALIGNED(16, int16_t, tmp[MAX_PB_SIZE * MAX_PB_SIZE]); DECLARE_ALIGNED(16, int16_t, tmp2[MAX_PB_SIZE * MAX_PB_SIZE]); luma_mc(s, tmp, tmpstride, ref0->frame, &current_mv.mv[0], x0, y0, nPbW, nPbH); if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) || (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) { s->hevcdsp.weighted_pred(s->sh.luma_log2_weight_denom, s->sh.luma_weight_l0[current_mv.ref_idx[0]], s->sh.luma_offset_l0[current_mv.ref_idx[0]], dst0, s->frame->linesize[0], tmp, tmpstride, nPbW, nPbH); } else { s->hevcdsp.put_unweighted_pred(dst0, s->frame->linesize[0], tmp, tmpstride, nPbW, nPbH); } chroma_mc(s, tmp, tmp2, tmpstride, ref0->frame, &current_mv.mv[0], x0 / 2, y0 / 2, nPbW / 2, nPbH / 2); if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) || (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) { s->hevcdsp.weighted_pred(s->sh.chroma_log2_weight_denom, s->sh.chroma_weight_l0[current_mv.ref_idx[0]][0], s->sh.chroma_offset_l0[current_mv.ref_idx[0]][0], dst1, s->frame->linesize[1], tmp, tmpstride, nPbW / 2, nPbH / 2); s->hevcdsp.weighted_pred(s->sh.chroma_log2_weight_denom, s->sh.chroma_weight_l0[current_mv.ref_idx[0]][1], s->sh.chroma_offset_l0[current_mv.ref_idx[0]][1], dst2, s->frame->linesize[2], tmp2, tmpstride, nPbW / 2, nPbH / 2); } else { s->hevcdsp.put_unweighted_pred(dst1, s->frame->linesize[1], tmp, tmpstride, nPbW/2, nPbH/2); s->hevcdsp.put_unweighted_pred(dst2, s->frame->linesize[2], tmp2, tmpstride, nPbW/2, nPbH/2); } } else if (!current_mv.pred_flag[0] && current_mv.pred_flag[1]) { DECLARE_ALIGNED(16, int16_t, tmp [MAX_PB_SIZE * MAX_PB_SIZE]); DECLARE_ALIGNED(16, int16_t, tmp2[MAX_PB_SIZE * MAX_PB_SIZE]); if (!ref1) return; luma_mc(s, tmp, tmpstride, ref1->frame, &current_mv.mv[1], x0, y0, nPbW, nPbH); if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) || (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) { s->hevcdsp.weighted_pred(s->sh.luma_log2_weight_denom, s->sh.luma_weight_l1[current_mv.ref_idx[1]], s->sh.luma_offset_l1[current_mv.ref_idx[1]], dst0, s->frame->linesize[0], tmp, tmpstride, nPbW, nPbH); } else { s->hevcdsp.put_unweighted_pred(dst0, s->frame->linesize[0], tmp, tmpstride, nPbW, nPbH); } chroma_mc(s, tmp, tmp2, tmpstride, ref1->frame, &current_mv.mv[1], x0/2, y0/2, nPbW/2, nPbH/2); if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) || (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) { s->hevcdsp.weighted_pred(s->sh.chroma_log2_weight_denom, s->sh.chroma_weight_l1[current_mv.ref_idx[1]][0], s->sh.chroma_offset_l1[current_mv.ref_idx[1]][0], dst1, s->frame->linesize[1], tmp, tmpstride, nPbW/2, nPbH/2); s->hevcdsp.weighted_pred(s->sh.chroma_log2_weight_denom, s->sh.chroma_weight_l1[current_mv.ref_idx[1]][1], s->sh.chroma_offset_l1[current_mv.ref_idx[1]][1], dst2, s->frame->linesize[2], tmp2, tmpstride, nPbW/2, nPbH/2); } else { s->hevcdsp.put_unweighted_pred(dst1, s->frame->linesize[1], tmp, tmpstride, nPbW/2, nPbH/2); s->hevcdsp.put_unweighted_pred(dst2, s->frame->linesize[2], tmp2, tmpstride, nPbW/2, nPbH/2); } } else if (current_mv.pred_flag[0] && current_mv.pred_flag[1]) { DECLARE_ALIGNED(16, int16_t, tmp [MAX_PB_SIZE * MAX_PB_SIZE]); DECLARE_ALIGNED(16, int16_t, tmp2[MAX_PB_SIZE * MAX_PB_SIZE]); DECLARE_ALIGNED(16, int16_t, tmp3[MAX_PB_SIZE * MAX_PB_SIZE]); DECLARE_ALIGNED(16, int16_t, tmp4[MAX_PB_SIZE * MAX_PB_SIZE]); HEVCFrame *ref0 = refPicList[0].ref[current_mv.ref_idx[0]]; HEVCFrame *ref1 = refPicList[1].ref[current_mv.ref_idx[1]]; if (!ref0 || !ref1) return; luma_mc(s, tmp, tmpstride, ref0->frame, &current_mv.mv[0], x0, y0, nPbW, nPbH); luma_mc(s, tmp2, tmpstride, ref1->frame, &current_mv.mv[1], x0, y0, nPbW, nPbH); if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) || (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) { s->hevcdsp.weighted_pred_avg(s->sh.luma_log2_weight_denom, s->sh.luma_weight_l0[current_mv.ref_idx[0]], s->sh.luma_weight_l1[current_mv.ref_idx[1]], s->sh.luma_offset_l0[current_mv.ref_idx[0]], s->sh.luma_offset_l1[current_mv.ref_idx[1]], dst0, s->frame->linesize[0], tmp, tmp2, tmpstride, nPbW, nPbH); } else { s->hevcdsp.put_weighted_pred_avg(dst0, s->frame->linesize[0], tmp, tmp2, tmpstride, nPbW, nPbH); } chroma_mc(s, tmp, tmp2, tmpstride, ref0->frame, &current_mv.mv[0], x0 / 2, y0 / 2, nPbW / 2, nPbH / 2); chroma_mc(s, tmp3, tmp4, tmpstride, ref1->frame, &current_mv.mv[1], x0 / 2, y0 / 2, nPbW / 2, nPbH / 2); if ((s->sh.slice_type == P_SLICE && s->pps->weighted_pred_flag) || (s->sh.slice_type == B_SLICE && s->pps->weighted_bipred_flag)) { s->hevcdsp.weighted_pred_avg(s->sh.chroma_log2_weight_denom, s->sh.chroma_weight_l0[current_mv.ref_idx[0]][0], s->sh.chroma_weight_l1[current_mv.ref_idx[1]][0], s->sh.chroma_offset_l0[current_mv.ref_idx[0]][0], s->sh.chroma_offset_l1[current_mv.ref_idx[1]][0], dst1, s->frame->linesize[1], tmp, tmp3, tmpstride, nPbW / 2, nPbH / 2); s->hevcdsp.weighted_pred_avg(s->sh.chroma_log2_weight_denom, s->sh.chroma_weight_l0[current_mv.ref_idx[0]][1], s->sh.chroma_weight_l1[current_mv.ref_idx[1]][1], s->sh.chroma_offset_l0[current_mv.ref_idx[0]][1], s->sh.chroma_offset_l1[current_mv.ref_idx[1]][1], dst2, s->frame->linesize[2], tmp2, tmp4, tmpstride, nPbW / 2, nPbH / 2); } else { s->hevcdsp.put_weighted_pred_avg(dst1, s->frame->linesize[1], tmp, tmp3, tmpstride, nPbW/2, nPbH/2); s->hevcdsp.put_weighted_pred_avg(dst2, s->frame->linesize[2], tmp2, tmp4, tmpstride, nPbW/2, nPbH/2); } } }
1,541
1
static void dma_rx(struct b43_dmaring *ring, int *slot) { const struct b43_dma_ops *ops = ring->ops; struct b43_dmadesc_generic *desc; struct b43_dmadesc_meta *meta; struct b43_rxhdr_fw4 *rxhdr; struct sk_buff *skb; u16 len; int err; dma_addr_t dmaaddr; desc = ops->idx2desc(ring, *slot, &meta); sync_descbuffer_for_cpu(ring, meta->dmaaddr, ring->rx_buffersize); skb = meta->skb; rxhdr = (struct b43_rxhdr_fw4 *)skb->data; len = le16_to_cpu(rxhdr->frame_len); if (len == 0) { int i = 0; do { udelay(2); barrier(); len = le16_to_cpu(rxhdr->frame_len); } while (len == 0 && i++ < 5); if (unlikely(len == 0)) { dmaaddr = meta->dmaaddr; goto drop_recycle_buffer; } } if (unlikely(b43_rx_buffer_is_poisoned(ring, skb))) { /* Something went wrong with the DMA. * The device did not touch the buffer and did not overwrite the poison. */ b43dbg(ring->dev->wl, "DMA RX: Dropping poisoned buffer.\n"); dmaaddr = meta->dmaaddr; goto drop_recycle_buffer; } if (unlikely(len > ring->rx_buffersize)) { /* The data did not fit into one descriptor buffer * and is split over multiple buffers. * This should never happen, as we try to allocate buffers * big enough. So simply ignore this packet. */ int cnt = 0; s32 tmp = len; while (1) { desc = ops->idx2desc(ring, *slot, &meta); /* recycle the descriptor buffer. */ b43_poison_rx_buffer(ring, meta->skb); sync_descbuffer_for_device(ring, meta->dmaaddr, ring->rx_buffersize); *slot = next_slot(ring, *slot); cnt++; tmp -= ring->rx_buffersize; if (tmp <= 0) break; } b43err(ring->dev->wl, "DMA RX buffer too small " "(len: %u, buffer: %u, nr-dropped: %d)\n", len, ring->rx_buffersize, cnt); goto drop; } dmaaddr = meta->dmaaddr; err = setup_rx_descbuffer(ring, desc, meta, GFP_ATOMIC); if (unlikely(err)) { b43dbg(ring->dev->wl, "DMA RX: setup_rx_descbuffer() failed\n"); goto drop_recycle_buffer; } unmap_descbuffer(ring, dmaaddr, ring->rx_buffersize, 0); skb_put(skb, len + ring->frameoffset); skb_pull(skb, ring->frameoffset); b43_rx(ring->dev, skb, rxhdr); drop: return; drop_recycle_buffer: /* Poison and recycle the RX buffer. */ b43_poison_rx_buffer(ring, skb); sync_descbuffer_for_device(ring, dmaaddr, ring->rx_buffersize); }
static void dma_rx(struct b43_dmaring *ring, int *slot) { const struct b43_dma_ops *ops = ring->ops; struct b43_dmadesc_generic *desc; struct b43_dmadesc_meta *meta; struct b43_rxhdr_fw4 *rxhdr; struct sk_buff *skb; u16 len; int err; dma_addr_t dmaaddr; desc = ops->idx2desc(ring, *slot, &meta); sync_descbuffer_for_cpu(ring, meta->dmaaddr, ring->rx_buffersize); skb = meta->skb; rxhdr = (struct b43_rxhdr_fw4 *)skb->data; len = le16_to_cpu(rxhdr->frame_len); if (len == 0) { int i = 0; do { udelay(2); barrier(); len = le16_to_cpu(rxhdr->frame_len); } while (len == 0 && i++ < 5); if (unlikely(len == 0)) { dmaaddr = meta->dmaaddr; goto drop_recycle_buffer; } } if (unlikely(b43_rx_buffer_is_poisoned(ring, skb))) { b43dbg(ring->dev->wl, "DMA RX: Dropping poisoned buffer.\n"); dmaaddr = meta->dmaaddr; goto drop_recycle_buffer; } if (unlikely(len > ring->rx_buffersize)) { int cnt = 0; s32 tmp = len; while (1) { desc = ops->idx2desc(ring, *slot, &meta); b43_poison_rx_buffer(ring, meta->skb); sync_descbuffer_for_device(ring, meta->dmaaddr, ring->rx_buffersize); *slot = next_slot(ring, *slot); cnt++; tmp -= ring->rx_buffersize; if (tmp <= 0) break; } b43err(ring->dev->wl, "DMA RX buffer too small " "(len: %u, buffer: %u, nr-dropped: %d)\n", len, ring->rx_buffersize, cnt); goto drop; } dmaaddr = meta->dmaaddr; err = setup_rx_descbuffer(ring, desc, meta, GFP_ATOMIC); if (unlikely(err)) { b43dbg(ring->dev->wl, "DMA RX: setup_rx_descbuffer() failed\n"); goto drop_recycle_buffer; } unmap_descbuffer(ring, dmaaddr, ring->rx_buffersize, 0); skb_put(skb, len + ring->frameoffset); skb_pull(skb, ring->frameoffset); b43_rx(ring->dev, skb, rxhdr); drop: return; drop_recycle_buffer: b43_poison_rx_buffer(ring, skb); sync_descbuffer_for_device(ring, dmaaddr, ring->rx_buffersize); }
1,542