dcf9d30cb27541e9411f1f5e61ee8b8dba3a2907
[platform/core/test/security-tests.git] / src / common / synchronization_pipe.cpp
1 /*
2  * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
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  * @file        synchronization_pipe.cpp
18  * @author      Aleksander Zdyb <a.zdyb@samsung.com>
19  * @version     1.0
20  * @brief       A crippled abstraction of widely praised, but often misused communication mechanism
21  */
22
23 #include <stdexcept>
24 #include <unistd.h>
25
26 #include <dpl/test/test_runner.h>
27
28 #include "synchronization_pipe.h"
29
30 static void closeFd(int *fd) {
31     if (*fd > -1) {
32         close(*fd);
33         *fd = -1;
34     }
35 }
36
37 SynchronizationPipe::SynchronizationPipe() {
38     auto ret = pipe(m_pipeCP);
39     RUNNER_ASSERT_ERRNO_MSG(ret == 0, "pipe failed");
40
41     ret = pipe(m_pipePC);
42     RUNNER_ASSERT_ERRNO_MSG(ret == 0, "pipe failed");
43 }
44
45 SynchronizationPipe::~SynchronizationPipe() {
46     closeFd(m_pipeCP + 0);
47     closeFd(m_pipeCP + 1);
48     closeFd(m_pipePC + 0);
49     closeFd(m_pipePC + 1);
50 }
51
52 void SynchronizationPipe::claimParentEp() {
53     if (m_epClaimed)
54         return;
55
56     m_readEp = m_pipeCP[0];
57     closeFd(m_pipeCP + 1);
58
59     m_writeEp = m_pipePC[1];
60     closeFd(m_pipePC + 0);
61
62     m_epClaimed = true;
63 }
64
65 void SynchronizationPipe::claimChildEp() {
66     if (m_epClaimed)
67         return;
68
69     m_readEp = m_pipePC[0];
70     closeFd(m_pipePC + 1);
71
72     m_writeEp = m_pipeCP[1];
73     closeFd(m_pipeCP + 0);
74
75     m_epClaimed = true;
76 }
77
78 void SynchronizationPipe::post() {
79     RUNNER_ASSERT_MSG(m_epClaimed == true, "Endpoint not claimed");
80     auto ret = TEMP_FAILURE_RETRY(write(m_writeEp, "#", 1));
81     RUNNER_ASSERT_ERRNO_MSG(ret > 0, "Write failed ret = " << ret);
82 }
83
84 void SynchronizationPipe::wait() {
85     RUNNER_ASSERT_MSG(m_epClaimed == true, "Endpoint not claimed");
86
87     char buf;
88     auto ret = TEMP_FAILURE_RETRY(read(m_readEp, &buf, 1));
89     RUNNER_ASSERT_ERRNO_MSG(ret > 0, "Read failed ret = " << ret);
90 }