1 /*
2  * Copyright 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ANDROID_AUDIO_STRING_H
18 #define ANDROID_AUDIO_STRING_H
19 
20 #include <string.h>
21 
22 /** similar to strlcpy but also zero fills to end of string buffer, ensures no data leak
23     in parceled data sent over binder.*/
audio_utils_strlcpy_zerofill(char * dst,const char * src,size_t dst_size)24 inline size_t audio_utils_strlcpy_zerofill(char *dst, const char *src, size_t dst_size) {
25     const size_t srclen = strlcpy(dst, src, dst_size);
26     const size_t srclen_with_zero = srclen + 1; /* include zero termination in length. */
27     if (srclen_with_zero < dst_size) {
28         const size_t num_zeroes = dst_size - srclen_with_zero;
29         memset(dst + srclen_with_zero, 0 /* value */, num_zeroes); /* clear remaining buffer */
30     }
31     return srclen;
32 }
33 
34 #ifdef __cplusplus
35 
36 /** similar to audio_utils_strlcpy_zerofill for fixed size destination string. */
37 template <size_t size>
audio_utils_strlcpy_zerofill(char (& dst)[size],const char * src)38 inline size_t audio_utils_strlcpy_zerofill(char (&dst)[size], const char *src) {
39     return audio_utils_strlcpy_zerofill(dst, src, size);
40 }
41 
42 /** similar to strlcpy for fixed size destination string. */
43 template <size_t size>
audio_utils_strlcpy(char (& dst)[size],const char * src)44 inline size_t audio_utils_strlcpy(char (&dst)[size], const char *src) {
45     return strlcpy(dst, src, size);
46 }
47 
48 #endif // __cplusplus
49 
50 #endif // !ANDROID_AUDIO_STRING_H
51