• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include <fcntl.h>
16 #include <grp.h>
17 #include <inttypes.h>
18 #include <limits.h>
19 #include <sys/capability.h>
20 #include <stdbool.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/ioctl.h>
25 #include <sys/mount.h>
26 #include <sys/prctl.h>
27 #include <sys/signalfd.h>
28 #include <sys/stat.h>
29 #include <sys/syscall.h>
30 #include <sys/types.h>
31 #include <sys/wait.h>
32 #include <unistd.h>
33 
34 #undef _GNU_SOURCE
35 #define _GNU_SOURCE
36 #include <dlfcn.h>
37 #include <malloc.h>
38 #include <sched.h>
39 
40 #include "appspawn_adapter.h"
41 #include "appspawn_hook.h"
42 #include "appspawn_service.h"
43 #include "appspawn_msg.h"
44 #include "appspawn_manager.h"
45 #include "appspawn_silk.h"
46 #include "init_param.h"
47 #include "parameter.h"
48 #include "securec.h"
49 
50 #ifdef CODE_SIGNATURE_ENABLE  // for xpm
51 #include "code_sign_attr_utils.h"
52 #endif
53 #ifdef SECURITY_COMPONENT_ENABLE
54 #include "sec_comp_enhance_kit_c.h"
55 #endif
56 #ifdef WITH_SELINUX
57 #include "selinux/selinux.h"
58 #endif
59 
60 #define PROVISION_TYPE_DEBUG "debug"
61 #define DEVICE_NULL_STR "/dev/null"
62 #define BITLEN32 32
63 #define PID_NS_INIT_UID 100000  // reserved for pid_ns_init process, avoid app, render proc, etc.
64 #define PID_NS_INIT_GID 100000
65 
SetProcessName(const AppSpawnMgr * content,const AppSpawningCtx * property)66 static int SetProcessName(const AppSpawnMgr *content, const AppSpawningCtx *property)
67 {
68     const char *processName = GetProcessName(property);
69     APPSPAWN_CHECK(processName != NULL, return -EINVAL, "Can not get process name");
70     // 解析时已经检查
71     size_t len = strlen(processName);
72     char shortName[MAX_LEN_SHORT_NAME] = {0};
73     // process short name max length 16 bytes.
74     size_t copyLen = len;
75     const char *pos = processName;
76     if (len >= MAX_LEN_SHORT_NAME) {
77         copyLen = MAX_LEN_SHORT_NAME - 1;
78         pos += (len - copyLen);
79     }
80     bool isRet = strncpy_s(shortName, MAX_LEN_SHORT_NAME, pos, copyLen) != EOK;
81     APPSPAWN_CHECK(!isRet, return EINVAL, "strncpy_s short name error: %{public}d", errno);
82 
83     // set short name
84     isRet = prctl(PR_SET_NAME, shortName) == -1;
85     APPSPAWN_CHECK(!isRet, return errno, "prctl(PR_SET_NAME) error: %{public}d", errno);
86 
87     // reset longProcName
88     isRet = memset_s(content->content.longProcName,
89         (size_t)content->content.longProcNameLen, 0, (size_t)content->content.longProcNameLen) != EOK;
90     APPSPAWN_CHECK(!isRet, return EINVAL, "Failed to memset long process name");
91 
92     // set long process name
93     isRet = strncpy_s(content->content.longProcName, content->content.longProcNameLen, processName, len) != EOK;
94     APPSPAWN_CHECK(!isRet, return EINVAL,
95         "strncpy_s long name error: %{public}d longProcNameLen %{public}u", errno, content->content.longProcNameLen);
96     return 0;
97 }
98 
SetKeepCapabilities(const AppSpawnMgr * content,const AppSpawningCtx * property)99 static int SetKeepCapabilities(const AppSpawnMgr *content, const AppSpawningCtx *property)
100 {
101     AppSpawnMsgDacInfo *dacInfo = (AppSpawnMsgDacInfo *)GetAppProperty(property, TLV_DAC_INFO);
102     APPSPAWN_CHECK(dacInfo != NULL, return APPSPAWN_TLV_NONE,
103         "No tlv %{public}d in msg %{public}s", TLV_DOMAIN_INFO, GetProcessName(property));
104 
105     // set keep capabilities when user not root.
106     if (dacInfo->uid != 0) {
107         bool isRet = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1;
108         APPSPAWN_CHECK(!isRet, return errno, "set keepcaps failed: %{public}d", errno);
109     }
110     return 0;
111 }
112 
SetCapabilities(const AppSpawnMgr * content,const AppSpawningCtx * property)113 static int SetCapabilities(const AppSpawnMgr *content, const AppSpawningCtx *property)
114 {
115     // init cap
116     struct __user_cap_header_struct capHeader;
117 
118     bool isRet = memset_s(&capHeader, sizeof(capHeader), 0, sizeof(capHeader)) != EOK;
119     APPSPAWN_CHECK(!isRet, return -EINVAL, "Failed to memset cap header");
120 
121     capHeader.version = _LINUX_CAPABILITY_VERSION_3;
122     capHeader.pid = 0;
123 
124     struct __user_cap_data_struct capData[2]; // 2 is data number
125     isRet = memset_s(&capData, sizeof(capData), 0, sizeof(capData)) != EOK;
126     APPSPAWN_CHECK(!isRet, return -EINVAL, "Failed to memset cap data");
127 
128     // init inheritable permitted effective zero
129 #ifdef GRAPHIC_PERMISSION_CHECK
130     const uint64_t inheriTable = 0;
131     const uint64_t permitted = 0;
132     const uint64_t effective = 0;
133 #else
134     const uint64_t inheriTable = 0x3fffffffff;
135     const uint64_t permitted = 0x3fffffffff;
136     const uint64_t effective = 0x3fffffffff;
137 #endif
138 
139     capData[0].inheritable = (__u32)(inheriTable);
140     capData[1].inheritable = (__u32)(inheriTable >> BITLEN32);
141     capData[0].permitted = (__u32)(permitted);
142     capData[1].permitted = (__u32)(permitted >> BITLEN32);
143     capData[0].effective = (__u32)(effective);
144     capData[1].effective = (__u32)(effective >> BITLEN32);
145 
146     // set capabilities
147     isRet = capset(&capHeader, &capData[0]) != 0;
148     APPSPAWN_CHECK(!isRet, return -errno, "Failed to capset errno: %{public}d", errno);
149     return 0;
150 }
151 
InitDebugParams(const AppSpawnMgr * content,const AppSpawningCtx * property)152 static void InitDebugParams(const AppSpawnMgr *content, const AppSpawningCtx *property)
153 {
154 #if defined(__aarch64__) || defined(__x86_64__)
155     const char *debugSoPath = "/system/lib64/libhidebug.so";
156 #else
157     const char *debugSoPath = "/system/lib/libhidebug.so";
158 #endif
159     const char *processName = GetProcessName(property);
160     APPSPAWN_CHECK(processName != NULL, return, "Can not get process name");
161 
162     bool isRet = access(debugSoPath, F_OK) != 0;
163     APPSPAWN_CHECK(!isRet, return,
164         "access failed, errno: %{public}d debugSoPath: %{public}s", errno, debugSoPath);
165 
166     void *handle = dlopen(debugSoPath, RTLD_LAZY);
167     APPSPAWN_CHECK(handle != NULL, return, "Failed to dlopen libhidebug.so errno: %{public}s", dlerror());
168 
169     bool (*initParam)(const char *name);
170     initParam = (bool (*)(const char *name))dlsym(handle, "InitEnvironmentParam");
171     APPSPAWN_CHECK(initParam != NULL, dlclose(handle);
172         return, "Failed to dlsym errno: %{public}s", dlerror());
173     (*initParam)(processName);
174     dlclose(handle);
175 }
176 
ClearEnvironment(const AppSpawnMgr * content,const AppSpawningCtx * property)177 static void ClearEnvironment(const AppSpawnMgr *content, const AppSpawningCtx *property)
178 {
179     sigset_t mask;
180     sigemptyset(&mask);
181     sigaddset(&mask, SIGCHLD);
182     sigaddset(&mask, SIGTERM);
183     sigprocmask(SIG_UNBLOCK, &mask, NULL);
184     // close child fd
185     AppSpawningCtx *ctx = (AppSpawningCtx *)property;
186     close(ctx->forkCtx.fd[0]);
187     ctx->forkCtx.fd[0] = -1;
188     return;
189 }
190 
SetXpmConfig(const AppSpawnMgr * content,const AppSpawningCtx * property)191 static int SetXpmConfig(const AppSpawnMgr *content, const AppSpawningCtx *property)
192 {
193 #ifdef CODE_SIGNATURE_ENABLE
194     // nwebspawn no permission set xpm config
195     if (IsNWebSpawnMode(content)) {
196         return 0;
197     }
198 
199     uint32_t len = 0;
200     char *provisionType = GetAppPropertyExt(property, MSG_EXT_NAME_PROVISION_TYPE, &len);
201     if (provisionType == NULL || len == 0) {
202         APPSPAWN_LOGE("get provision type failed, defaut is %{public}s", PROVISION_TYPE_DEBUG);
203         provisionType = PROVISION_TYPE_DEBUG;
204     }
205 
206     AppSpawnMsgOwnerId *ownerInfo = (AppSpawnMsgOwnerId *)GetAppProperty(property, TLV_OWNER_INFO);
207     int jitfortEnable = IsJitFortModeOn(property) ? 1 : 0;
208     int idType = PROCESS_OWNERID_UNINIT;
209     const char *ownerId = NULL;
210     if (strcmp(provisionType, PROVISION_TYPE_DEBUG) == 0) {
211         idType = PROCESS_OWNERID_DEBUG;
212     } else if (ownerInfo == NULL) {
213         idType = PROCESS_OWNERID_COMPAT;
214     } else if (CheckAppMsgFlagsSet(property, APP_FLAGS_TEMP_JIT)) {
215         idType = PROCESS_OWNERID_APP_TEMP_ALLOW;
216         ownerId = ownerInfo->ownerId;
217     } else {
218         idType = PROCESS_OWNERID_APP;
219         ownerId = ownerInfo->ownerId;
220     }
221     int ret = InitXpm(jitfortEnable, idType, ownerId);
222     APPSPAWN_CHECK(ret == 0, return ret, "set xpm region failed: %{public}d", ret);
223 #endif
224     return 0;
225 }
226 
SetUidGid(const AppSpawnMgr * content,const AppSpawningCtx * property)227 static int SetUidGid(const AppSpawnMgr *content, const AppSpawningCtx *property)
228 {
229     if (IsAppSpawnMode(content)) {
230         struct sched_param param = { 0 };
231         param.sched_priority = 0;
232         int ret = sched_setscheduler(0, SCHED_OTHER, &param);
233         APPSPAWN_CHECK_ONLY_LOG(ret == 0, "UpdateSchedPrio failed ret: %{public}d, %{public}d", ret, errno);
234     }
235     AppSpawnMsgDacInfo *dacInfo = (AppSpawnMsgDacInfo *)GetAppProperty(property, TLV_DAC_INFO);
236     APPSPAWN_CHECK(dacInfo != NULL, return APPSPAWN_TLV_NONE,
237         "No tlv %{public}d in msg %{public}s", TLV_DAC_INFO, GetProcessName(property));
238 
239     // set gids
240     int ret = setgroups(dacInfo->gidCount, (const gid_t *)(&dacInfo->gidTable[0]));
241     APPSPAWN_CHECK(ret == 0, return errno,
242         "setgroups failed: %{public}d, gids.size=%{public}u", errno, dacInfo->gidCount);
243 
244     // set gid
245     if (IsNWebSpawnMode(content)) {
246         gid_t gid = dacInfo->gid / UID_BASE;
247         if (gid >= 100) { // 100
248             APPSPAWN_LOGE("SetUidGid invalid uid for nwebspawn %{public}d", dacInfo->gid);
249             return 0;
250         }
251         ret = setresgid(dacInfo->gid, dacInfo->gid, dacInfo->gid);
252     } else {
253         ret = setresgid(dacInfo->gid, dacInfo->gid, dacInfo->gid);
254     }
255     APPSPAWN_CHECK(ret == 0, return errno,
256         "setgid(%{public}u) failed: %{public}d", dacInfo->gid, errno);
257 
258     ret = SetSeccompFilter(content, property);
259     APPSPAWN_CHECK(ret == 0, return ret, "Failed to set setSeccompFilter");
260 
261     /* If the effective user ID is changed from 0 to nonzero,
262      * then all capabilities are cleared from the effective set
263      */
264     ret = setresuid(dacInfo->uid, dacInfo->uid, dacInfo->uid);
265     APPSPAWN_CHECK(ret == 0, return errno,
266         "setuid(%{public}u) failed: %{public}d", dacInfo->uid, errno);
267 
268     if (CheckAppMsgFlagsSet(property, APP_FLAGS_DEBUGGABLE) && IsDeveloperModeOn(property)) {
269         setenv("HAP_DEBUGGABLE", "true", 1);
270         if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
271             APPSPAWN_LOGE("Failed to set app dumpable: %{public}s", strerror(errno));
272         }
273     } else {
274         setenv("HAP_DEBUGGABLE", "false", 1);
275     }
276     return 0;
277 }
278 
SetFileDescriptors(const AppSpawnMgr * content,const AppSpawningCtx * property)279 static int32_t SetFileDescriptors(const AppSpawnMgr *content, const AppSpawningCtx *property)
280 {
281 #ifndef APPSPAWN_TEST
282     // redirect stdin stdout stderr to /dev/null
283     int devNullFd = open(DEVICE_NULL_STR, O_RDWR);
284     if (devNullFd == -1) {
285         APPSPAWN_LOGE("open dev_null error: %{public}d", errno);
286         return (-errno);
287     }
288 
289     // stdin
290     if (dup2(devNullFd, STDIN_FILENO) == -1) {
291         APPSPAWN_LOGE("dup2 STDIN error: %{public}d", errno);
292         return (-errno);
293     }
294     // stdout
295     if (dup2(devNullFd, STDOUT_FILENO) == -1) {
296         APPSPAWN_LOGE("dup2 STDOUT error: %{public}d", errno);
297         return (-errno);
298     }
299     // stderr
300     if (dup2(devNullFd, STDERR_FILENO) == -1) {
301         APPSPAWN_LOGE("dup2 STDERR error: %{public}d", errno);
302         return (-errno);
303     }
304 
305     if (devNullFd > STDERR_FILENO) {
306         close(devNullFd);
307     }
308 #endif
309     return 0;
310 }
311 
CheckTraceStatus(void)312 static int32_t CheckTraceStatus(void)
313 {
314     int fd = open("/proc/self/status", O_RDONLY);
315     APPSPAWN_CHECK(fd >= 0, return errno, "Failed to open /proc/self/status error: %{public}d", errno);
316 
317     char data[1024] = {0};  // 1024 is data length
318     ssize_t dataNum = read(fd, data, sizeof(data) - 1);
319     (void)close(fd);
320     APPSPAWN_CHECK(dataNum > 0, return -1, "Failed to read file /proc/self/status error: %{public}d", errno);
321 
322     const char *tracerPid = "TracerPid:\t";
323     data[dataNum] = '\0';
324     char *traceStr = strstr(data, tracerPid);
325     APPSPAWN_CHECK(traceStr != NULL, return -1, "Not found %{public}s", tracerPid);
326 
327     char *separator = strchr(traceStr, '\n');
328     APPSPAWN_CHECK(separator != NULL, return -1, "Not found %{public}s", "\n");
329 
330     int len = separator - traceStr - strlen(tracerPid);
331     char pid = *(traceStr + strlen(tracerPid));
332     if (len > 1 || pid != '0') {
333         return 0;
334     }
335     return -1;
336 }
337 
WaitForDebugger(const AppSpawningCtx * property)338 static int32_t WaitForDebugger(const AppSpawningCtx *property)
339 {
340     // wait for debugger only debugging is required and process is debuggable
341     if (CheckAppMsgFlagsSet(property, APP_FLAGS_NATIVEDEBUG) && CheckAppMsgFlagsSet(property, APP_FLAGS_DEBUGGABLE)) {
342         uint32_t count = 0;
343         while (CheckTraceStatus() != 0) {
344 #ifndef APPSPAWN_TEST
345             usleep(1000 * 100);  // sleep 1000 * 100 microsecond
346 #else
347             if (count > 0) {
348                 break;
349             }
350 #endif
351             count++;
352             // remind users to connect to the debugger every 60 * 10 times
353             if (count % (10 * 60) == 0) {
354                 count = 0;
355                 APPSPAWN_LOGI("wait for debugger, please attach the process");
356             }
357         }
358     }
359     return 0;
360 }
361 
SpawnInitSpawningEnv(AppSpawnMgr * content,AppSpawningCtx * property)362 static int SpawnInitSpawningEnv(AppSpawnMgr *content, AppSpawningCtx *property)
363 {
364     APPSPAWN_LOGV("Spawning: clear env");
365     int ret = SetProcessName(content, property);
366     APPSPAWN_CHECK_ONLY_EXPER(ret == 0, return ret);
367     // close socket id and signal for child
368     ClearEnvironment(content, property);
369 
370     ResetParamSecurityLabel();
371 
372     ret = SetAppAccessToken(content, property);
373     APPSPAWN_CHECK_ONLY_EXPER(ret == 0, return ret);
374     return 0;
375 }
376 
SpawnSetAppEnv(AppSpawnMgr * content,AppSpawningCtx * property)377 static int SpawnSetAppEnv(AppSpawnMgr *content, AppSpawningCtx *property)
378 {
379     APPSPAWN_LOGV("Spawning: set appEnv");
380     int ret = SetEnvInfo(content, property);
381     APPSPAWN_CHECK_ONLY_EXPER(ret == 0, return ret);
382     return 0;
383 }
384 
SpawnEnableCache(AppSpawnMgr * content,AppSpawningCtx * property)385 static int SpawnEnableCache(AppSpawnMgr *content, AppSpawningCtx *property)
386 {
387     APPSPAWN_LOGV("Spawning: enable cache for app process");
388     // enable cache for app process
389     mallopt(M_OHOS_CONFIG, M_TCACHE_PERFORMANCE_MODE);
390     mallopt(M_OHOS_CONFIG, M_ENABLE_OPT_TCACHE);
391     mallopt(M_SET_THREAD_CACHE, M_THREAD_CACHE_ENABLE);
392     mallopt(M_DELAYED_FREE, M_DELAYED_FREE_ENABLE);
393 
394     int ret = SetInternetPermission(property);
395     APPSPAWN_CHECK_ONLY_EXPER(ret == 0, return ret);
396     return ret;
397 }
398 
SpawnLoadSilk(const AppSpawnMgr * content,const AppSpawningCtx * property)399 static void SpawnLoadSilk(const AppSpawnMgr *content, const AppSpawningCtx *property)
400 {
401     const char *processName = GetBundleName(property);
402     APPSPAWN_CHECK(processName != NULL, return, "Can not get bundle name");
403     LoadSilkLibrary(processName);
404 }
405 
SpawnSetProperties(AppSpawnMgr * content,AppSpawningCtx * property)406 static int SpawnSetProperties(AppSpawnMgr *content, AppSpawningCtx *property)
407 {
408     APPSPAWN_LOGV("Spawning: set child property");
409     SpawnLoadSilk(content, property);
410     (void)umask(DEFAULT_UMASK);
411     int ret = SetKeepCapabilities(content, property);
412     APPSPAWN_CHECK_ONLY_EXPER(ret == 0, return ret);
413     ret = SetXpmConfig(content, property);
414     APPSPAWN_CHECK_ONLY_EXPER(ret == 0, return ret);
415 
416     ret = SetProcessName(content, property);
417     APPSPAWN_CHECK_ONLY_EXPER(ret == 0, return ret);
418 
419     ret = SetUidGid(content, property);
420     APPSPAWN_CHECK_ONLY_EXPER(ret == 0, return ret);
421 
422     ret = SetFileDescriptors(content, property);
423     APPSPAWN_CHECK_ONLY_EXPER(ret == 0, return ret);
424 
425     ret = SetCapabilities(content, property);
426     APPSPAWN_CHECK_ONLY_EXPER(ret == 0, return ret);
427 
428     ret = SetSelinuxCon(content, property) == -1;
429     APPSPAWN_CHECK_ONLY_EXPER(ret == 0, return ret);
430 
431     ret = WaitForDebugger(property);
432     APPSPAWN_CHECK_ONLY_EXPER(ret == 0, return ret);
433 
434     APPSPAWN_ONLY_EXPER(GetAppSpawnMsgType(property) == MSG_SPAWN_NATIVE_PROCESS, return 0);
435 #ifdef SECURITY_COMPONENT_ENABLE
436     InitSecCompClientEnhance();
437 #endif
438     return 0;
439 }
440 
PreLoadSetSeccompFilter(AppSpawnMgr * content)441 static int PreLoadSetSeccompFilter(AppSpawnMgr *content)
442 {
443     // set uid gid filetr
444     int ret = SetUidGidFilter(content);
445     APPSPAWN_CHECK_ONLY_EXPER(ret == 0, return ret);
446     return ret;
447 }
448 
SpawnComplete(AppSpawnMgr * content,AppSpawningCtx * property)449 static int SpawnComplete(AppSpawnMgr *content, AppSpawningCtx *property)
450 {
451     InitDebugParams(content, property);
452     return 0;
453 }
454 
CheckEnabled(const char * param,const char * value)455 static int CheckEnabled(const char *param, const char *value)
456 {
457     char tmp[32] = {0};  // 32 max
458     int ret = GetParameter(param, "", tmp, sizeof(tmp));
459     APPSPAWN_LOGV("CheckEnabled key %{public}s ret %{public}d result: %{public}s", param, ret, tmp);
460     int enabled = (ret > 0 && strcmp(tmp, value) == 0);
461     return enabled;
462 }
463 
SpawnGetSpawningFlag(AppSpawnMgr * content,AppSpawningCtx * property)464 static int SpawnGetSpawningFlag(AppSpawnMgr *content, AppSpawningCtx *property)
465 {
466     APPSPAWN_LOGV("Spawning: prepare app %{public}s", GetProcessName(property));
467     if (CheckAppMsgFlagsSet(property, APP_FLAGS_COLD_BOOT)) {
468         // check cold start
469         property->client.flags |= CheckEnabled("startup.appspawn.cold.boot", "true") ? APP_COLD_START : 0;
470     }
471     if (CheckAppMsgFlagsSet(property, APP_FLAGS_BEGETCTL_BOOT)) {
472        // Start app from begetctl for debugging.
473         property->client.flags |=  APP_BEGETCTL_BOOT;
474         APPSPAWN_LOGI("Spawning: prepare app %{public}s, start from begetctl", GetProcessName(property));
475     }
476     property->client.flags |= content->flags;
477     return 0;
478 }
479 
SpawnLoadConfig(AppSpawnMgr * content)480 static int SpawnLoadConfig(AppSpawnMgr *content)
481 {
482     LoadSilkConfig();
483     // init flags that will not change until next reboot
484     content->flags |= CheckEnabled("const.security.developermode.state", "true") ? APP_DEVELOPER_MODE : 0;
485     content->flags |= CheckEnabled("persist.security.jitfort.disabled", "true") ? 0 : APP_JITFORT_MODE;
486     return 0;
487 }
488 
CloseFdArgs(AppSpawnMgr * content,AppSpawningCtx * property)489 static int CloseFdArgs(AppSpawnMgr *content, AppSpawningCtx *property)
490 {
491     APPSPAWN_CHECK(property != NULL && property->message != NULL
492         && property->message->connection != NULL,
493         return -1, "Get connection info failed");
494     int fdCount = property->message->connection->receiverCtx.fdCount;
495     int *fds = property->message->connection->receiverCtx.fds;
496     if (fds != NULL && fdCount > 0) {
497         for (int i = 0; i < fdCount; i++) {
498             if (fds[i] > 0) {
499                 close(fds[i]);
500             }
501         }
502     }
503     property->message->connection->receiverCtx.fdCount = 0;
504     return 0;
505 }
506 
SetFdEnv(AppSpawnMgr * content,AppSpawningCtx * property)507 APPSPAWN_STATIC int SetFdEnv(AppSpawnMgr *content, AppSpawningCtx *property)
508 {
509     APPSPAWN_CHECK_ONLY_EXPER(property != NULL, return -1);
510     APPSPAWN_CHECK_ONLY_EXPER(!property->isPrefork, return 0);
511     AppSpawnMsgNode *message = property->message;
512     APPSPAWN_CHECK_ONLY_EXPER(message != NULL && message->buffer != NULL && message->connection != NULL, return -1);
513     APPSPAWN_CHECK_ONLY_EXPER(message->tlvOffset != NULL, return -1);
514     int findFdIndex = 0;
515     AppSpawnMsgReceiverCtx recvCtx = message->connection->receiverCtx;
516     APPSPAWN_CHECK(recvCtx.fds != NULL && recvCtx.fdCount > 0, return 0,
517         "no need set fd info %{public}d, %{public}d", recvCtx.fds != NULL, recvCtx.fdCount);
518     char keyBuffer[APP_FDNAME_MAXLEN + sizeof(APP_FDENV_PREFIX)];
519     char value[sizeof(int)];
520 
521     for (uint32_t index = TLV_MAX; index < (TLV_MAX + message->tlvCount); index++) {
522         if (message->tlvOffset[index] == INVALID_OFFSET) {
523             return -1;
524         }
525         uint8_t *data = message->buffer + message->tlvOffset[index];
526         if (((AppSpawnTlv *)data)->tlvType != TLV_MAX) {
527             continue;
528         }
529         AppSpawnTlvExt *tlv = (AppSpawnTlvExt *)data;
530         if (strcmp(tlv->tlvName, MSG_EXT_NAME_APP_FD) != 0) {
531             continue;
532         }
533         APPSPAWN_CHECK(findFdIndex < recvCtx.fdCount && recvCtx.fds[findFdIndex] > 0, return -1,
534             "check set env args failed %{public}d, %{public}d, %{public}d",
535             findFdIndex, recvCtx.fdCount, recvCtx.fds[findFdIndex]);
536         APPSPAWN_CHECK(snprintf_s(keyBuffer, sizeof(keyBuffer), sizeof(keyBuffer) - 1, APP_FDENV_PREFIX"%s",
537             data + sizeof(AppSpawnTlvExt)) >= 0, return -1, "failed print env key %{public}d", errno);
538         APPSPAWN_CHECK(snprintf_s(value, sizeof(value), sizeof(value) - 1,
539             "%d", recvCtx.fds[findFdIndex++]) >= 0, return -1, "failed print env key %{public}d", errno);
540         int ret = setenv(keyBuffer, value, 1);
541         APPSPAWN_CHECK(ret == 0, return -1, "failed setenv %{public}s, %{public}s", keyBuffer, value);
542         if (findFdIndex >= recvCtx.fdCount) {
543             break;
544         }
545     }
546     return 0;
547 }
548 
MODULE_CONSTRUCTOR(void)549 MODULE_CONSTRUCTOR(void)
550 {
551     APPSPAWN_LOGV("Load common module ...");
552     AddPreloadHook(HOOK_PRIO_COMMON, PreLoadSetSeccompFilter);
553     AddPreloadHook(HOOK_PRIO_COMMON, SpawnLoadConfig);
554 
555     AddAppSpawnHook(STAGE_PARENT_PRE_FORK, HOOK_PRIO_HIGHEST, SpawnGetSpawningFlag);
556     AddAppSpawnHook(STAGE_CHILD_PRE_COLDBOOT, HOOK_PRIO_HIGHEST, SpawnInitSpawningEnv);
557     AddAppSpawnHook(STAGE_CHILD_PRE_COLDBOOT, HOOK_PRIO_COMMON + 1, SpawnSetAppEnv);
558     AddAppSpawnHook(STAGE_CHILD_EXECUTE, HOOK_PRIO_HIGHEST, SpawnEnableCache);
559     AddAppSpawnHook(STAGE_CHILD_EXECUTE, HOOK_PRIO_PROPERTY, SpawnSetProperties);
560     AddAppSpawnHook(STAGE_CHILD_POST_RELY, HOOK_PRIO_HIGHEST, SpawnComplete);
561     AddAppSpawnHook(STAGE_PARENT_POST_FORK, HOOK_PRIO_HIGHEST, CloseFdArgs);
562     AddAppSpawnHook(STAGE_CHILD_PRE_COLDBOOT, HOOK_PRIO_HIGHEST, SetFdEnv);
563 }
564