Debian Codegraph @

CodeLite/unixprocess_impl.cpp

raw
1 //////////////////////////////////////////////////////////////////////////////
2 //////////////////////////////////////////////////////////////////////////////
3 //
4 // copyright : (C) 2014 Eran Ifrah
5 // file name : unixprocess_impl.cpp
6 //
7 // -------------------------------------------------------------------------
8 // A
9 // _____ _ _ _ _
10 // / __ \ | | | | (_) |
11 // | / \/ ___ __| | ___| | _| |_ ___
12 // | | / _ \ / _ |/ _ \ | | | __/ _ )
13 // | \__/\ (_) | (_| | __/ |___| | || __/
14 // \____/\___/ \__,_|\___\_____/_|\__\___|
15 //
16 // F i l e
17 //
18 // This program is free software; you can redistribute it and/or modify
19 // it under the terms of the GNU General Public License as published by
20 // the Free Software Foundation; either version 2 of the License, or
21 // (at your option) any later version.
22 //
23 //////////////////////////////////////////////////////////////////////////////
24 //////////////////////////////////////////////////////////////////////////////
25
26 #include "unixprocess_impl.h"
27
28 #include "SocketAPI/clSocketBase.h"
29 #include "StringUtils.h"
30 #include "cl_exception.h"
31 #include "file_logger.h"
32 #include "fileutils.h"
33
34 #include <cstring>
35 #include <string>
36 #include <thread>
37 #include <wx/buffer.h>
38
39 #if defined(__WXMAC__) || defined(__WXGTK__)
40
41 #include "procutils.h"
42
43 #include <errno.h>
44 #include <signal.h>
45 #include <string.h>
46 #include <sys/select.h>
47 #include <sys/types.h>
48 #include <sys/wait.h>
49 #include <unistd.h>
50 #include <wx/filename.h>
51 #include <wx/stdpaths.h>
52
53 #ifdef __WXGTK__
54 #ifdef __FreeBSD__
55 #include <libutil.h>
56 #include <sys/ioctl.h>
57 #include <termios.h>
58 #elif defined(__NetBSD__)
59 #include <sys/ioctl.h>
60 #include <termios.h>
61 #include <util.h>
62 #else
63 #include <pty.h>
64 #include <utmp.h>
65 #endif
66 #else
67 #include <util.h>
68 #endif
69
70 // ----------------------------------------------
71 #define ISBLANK(ch) ((ch) == ' ' || (ch) == '\t')
72 #define BUFF_SIZE 1024 * 64
73
74 /* Routines imported from standard C runtime libraries. */
75
76 #ifdef __STDC__
77
78 #include <stddef.h>
79 #include <stdlib.h>
80 #include <string.h>
81
82 #else /* !__STDC__ */
83
84 #if !defined _WIN32 || defined __GNUC__
85 extern char* memcpy(); /* Copy memory region */
86 extern int strlen(); /* Count length of string */
87 extern char* malloc(); /* Standard memory allocater */
88 extern char* realloc(); /* Standard memory reallocator */
89 extern void free(); /* Free malloc'd memory */
90 extern char* strdup(); /* Duplicate a string */
91 #endif
92
93 #endif /* __STDC__ */
94
95 #ifndef NULL
96 #define NULL 0
97 #endif
98
99 #ifndef EOS
100 #define EOS '\0'
101 #endif
102
103 #define INITIAL_MAXARGC 8 /* Number of args + NULL in initial argv */
104
105 static void freeargv(char** vector)
106 {
107 char** scan;
108 if(vector != NULL) {
109 for(scan = vector; *scan != NULL; scan++) {
110 free(*scan);
111 }
112 delete[] vector;
113 }
114 }
115
116 //-----------------------------------------------------
117
118 static char** make_argv(const wxArrayString& args, int& argc)
119 {
120 char** argv = new char*[args.size() + 1];
121 for(size_t i = 0; i < args.size(); ++i) {
122 argv[i] = strdup(args[i].mb_str(wxConvUTF8).data());
123 }
124 argv[args.size()] = 0;
125 argc = args.size();
126 return argv;
127 }
128
129 static void RemoveTerminalColoring(char* buffer)
130 {
131 std::string cinput = buffer;
132 std::string coutout;
133 StringUtils::StripTerminalColouring(cinput, coutout);
134
135 // coutout is ALWAYS <= cinput, so we can safely copy the content to the buffer
136 if(coutout.length() < cinput.length()) {
137 strcpy(buffer, coutout.c_str());
138 }
139 }
140
141 UnixProcessImpl::UnixProcessImpl(wxEvtHandler* parent)
142 : IProcess(parent)
143 , m_readHandle(-1)
144 , m_writeHandle(-1)
145 {
146 }
147
148 UnixProcessImpl::~UnixProcessImpl() { Cleanup(); }
149
150 void UnixProcessImpl::Cleanup()
151 {
152 close(GetReadHandle());
153 close(GetWriteHandle());
154 if(GetStderrHandle() != wxNOT_FOUND) {
155 close(GetStderrHandle());
156 }
157 if(m_thr) {
158 // Stop the reader thread
159 m_thr->Stop();
160 delete m_thr;
161 }
162 m_thr = NULL;
163
164 if(GetPid() != wxNOT_FOUND) {
165 wxKill(GetPid(), GetHardKill() ? wxSIGKILL : wxSIGTERM, NULL, wxKILL_CHILDREN);
166 // The Zombie cleanup is done in app.cpp in ::ChildTerminatedSingalHandler() signal handler
167 int status(0);
168 waitpid(-1, &status, WNOHANG);
169 }
170 }
171
172 bool UnixProcessImpl::IsAlive() { return kill(m_pid, 0) == 0; }
173
174 bool UnixProcessImpl::ReadFromFd(int fd, fd_set& rset, wxString& output)
175 {
176 if(fd == wxNOT_FOUND) {
177 return false;
178 }
179 if(FD_ISSET(fd, &rset)) {
180 // there is something to read
181 char buffer[BUFF_SIZE + 1]; // our read buffer
182 int bytesRead = read(fd, buffer, sizeof(buffer));
183 if(bytesRead > 0) {
184 buffer[bytesRead] = 0; // always place a terminator
185
186 // Remove coloring chars from the incomnig buffer
187 // colors are marked with ESC and terminates with lower case 'm'
188 if(!(this->m_flags & IProcessRawOutput)) {
189 RemoveTerminalColoring(buffer);
190 }
191 wxString convBuff = wxString(buffer, wxConvUTF8);
192 if(convBuff.IsEmpty()) {
193 convBuff = wxString::From8BitData(buffer);
194 }
195
196 output.swap(convBuff);
197 return true;
198 }
199 }
200 return false;
201 }
202
203 bool UnixProcessImpl::Read(wxString& buff, wxString& buffErr)
204 {
205 fd_set rs;
206 timeval timeout;
207
208 memset(&rs, 0, sizeof(rs));
209 FD_SET(GetReadHandle(), &rs);
210 if(m_stderrHandle != wxNOT_FOUND) {
211 FD_SET(m_stderrHandle, &rs);
212 }
213
214 timeout.tv_sec = 0; // 0 seconds
215 timeout.tv_usec = 250000; // 250 ms
216
217 int errCode(0);
218 errno = 0;
219
220 buff.Clear();
221 int maxFd = wxMax(GetStderrHandle(), GetReadHandle());
222 int rc = select(maxFd + 1, &rs, NULL, NULL, &timeout);
223 errCode = errno;
224 if(rc == 0) {
225 // timeout
226 return true;
227
228 } else if(rc > 0) {
229 // We differentiate between stdout and stderr?
230 bool stderrRead = ReadFromFd(GetStderrHandle(), rs, buffErr);
231 bool stdoutRead = ReadFromFd(GetReadHandle(), rs, buff);
232 return stderrRead || stdoutRead;
233
234 } else {
235
236 if(errCode == EINTR || errCode == EAGAIN) {
237 return true;
238 }
239
240 // Process terminated
241 // the exit code will be set in the sigchld event handler
242 return false;
243 }
244 }
245
246 namespace
247 {
248 bool do_write(int fd, const wxMemoryBuffer& buffer)
249 {
250 static constexpr int max_retry_count = 10;
251 size_t bytes_written = 0;
252 size_t bytes_left = buffer.GetDataLen();
253
254 char* pdata = (char*)buffer.GetData();
255 std::string str(pdata, bytes_left);
256 LOG_IF_TRACE
257 {
258 clDEBUG1() << "do_write() buffer:" << str << endl;
259 clDEBUG1() << "do_write() length:" << str.length() << endl;
260 }
261 while(bytes_left) {
262 int bytes_sent = ::write(fd, (const char*)pdata, bytes_left);
263 LOG_IF_TRACE { clDEBUG1() << "::do_write() completed. number of bytes sent:" << bytes_sent << endl; }
264 if(bytes_sent <= 0) {
265 return false;
266 }
267 pdata += bytes_sent;
268 bytes_left -= bytes_sent;
269 }
270 return true;
271 }
272 } // namespace
273
274 bool UnixProcessImpl::Write(const std::string& buff) { return WriteRaw(buff + "\n"); }
275
276 bool UnixProcessImpl::Write(const wxString& buff) { return Write(FileUtils::ToStdString(buff)); }
277
278 bool UnixProcessImpl::WriteRaw(const wxString& buff) { return WriteRaw(FileUtils::ToStdString(buff)); }
279 bool UnixProcessImpl::WriteRaw(const std::string& buff)
280 {
281 int fd = GetWriteHandle();
282 wxMemoryBuffer mb;
283 mb.AppendData(buff.c_str(), buff.length());
284 return do_write(GetWriteHandle(), mb);
285 }
286
287 IProcess* UnixProcessImpl::Execute(wxEvtHandler* parent, const wxArrayString& args, size_t flags,
288 const wxString& workingDirectory, IProcessCallback* cb)
289 {
290 int argc = 0;
291 char** argv = make_argv(args, argc);
292 if(argc == 0 || argv == nullptr) {
293 return nullptr;
294 }
295
296 // fork the child process
297 wxString curdir = wxGetCwd();
298
299 // Prentend that we are a terminal...
300 int master;
301 char pts_name[1024];
302 memset(pts_name, 0x0, sizeof(pts_name));
303
304 // Create a one-way communication channel (pipe).
305 // If successful, two file descriptors are stored in stderrPipes;
306 // bytes written on stderrPipes[1] can be read from stderrPipes[0].
307 // Returns 0 if successful, -1 if not.
308 int stderrPipes[2] = { 0, 0 };
309 if(flags & IProcessStderrEvent) {
310 errno = 0;
311 if(pipe(stderrPipes) < 0) {
312 clERROR() << "Failed to create pipe for stderr redirecting." << strerror(errno);
313 flags &= ~IProcessStderrEvent;
314 }
315 }
316
317 int rc = forkpty(&master, pts_name, nullptr, nullptr);
318 if(rc == 0) {
319 //===-------------------------------------------------------
320 // Child process
321 //===-------------------------------------------------------
322 for(int i = 0; i < FD_SETSIZE; ++i) {
323 if(i != STDERR_FILENO && i != STDOUT_FILENO && i != STDIN_FILENO) {
324 if((i == stderrPipes[1]) && (flags & IProcessStderrEvent)) {
325 // skip it
326 } else {
327 ::close(i);
328 }
329 }
330 }
331
332 // Incase the user wants to get separate events for STDERR, dup2 STDERR to the PIPE write end
333 // we opened earlier
334 if(flags & IProcessStderrEvent) {
335 // Dup stderrPipes[1] into stderr
336 dup2(stderrPipes[1], STDERR_FILENO);
337 close(stderrPipes[1]);
338 }
339
340 // at this point, slave is used as stdin/stdout/stderr
341 // Child process
342 if(workingDirectory.IsEmpty() == false) {
343 wxSetWorkingDirectory(workingDirectory);
344 }
345
346 // execute the process
347 errno = 0;
348 if(execvp(argv[0], argv) < 0) {
349 clERROR() << "execvp" << args << "error:" << strerror(errno) << clEndl;
350 }
351
352 // if we got here, we failed...
353 exit(0);
354
355 } else if(rc < 0) {
356 // Error
357
358 // restore the working directory
359 wxSetWorkingDirectory(curdir);
360
361 return NULL;
362
363 } else {
364 //===-------------------------------------------------------
365 // Parent
366 //===-------------------------------------------------------
367 struct termios tios;
368 tcgetattr(master, &tios);
369 tios.c_lflag &= ~(ECHO | ECHONL);
370 tcsetattr(master, TCSAFLUSH, &tios);
371
372 freeargv(argv);
373 argc = 0;
374
375 // disable ECHO
376 struct termios termio;
377 tcgetattr(master, &termio);
378 cfmakeraw(&termio);
379 termio.c_lflag = ICANON;
380 termio.c_oflag = ONOCR | ONLRET;
381 tcsetattr(master, TCSANOW, &termio);
382
383 // restore the working directory
384 wxSetWorkingDirectory(curdir);
385
386 UnixProcessImpl* proc = new UnixProcessImpl(parent);
387 proc->m_callback = cb;
388 if(flags & IProcessStderrEvent) {
389 close(stderrPipes[1]); // close the write end
390 // set the stderr handle
391 proc->SetStderrHandle(stderrPipes[0]);
392 }
393
394 proc->SetReadHandle(master);
395 proc->SetWriteHandler(master);
396 proc->SetPid(rc);
397 proc->m_flags = flags; // Keep the creation flags
398
399 // Keep the terminal name, we will need it
400 proc->SetTty(pts_name);
401
402 if(!(proc->m_flags & IProcessCreateSync)) {
403 proc->StartReaderThread();
404 }
405 return proc;
406 }
407 }
408
409 IProcess* UnixProcessImpl::Execute(wxEvtHandler* parent, const wxString& cmd, size_t flags,
410 const wxString& workingDirectory, IProcessCallback* cb)
411 {
412 wxArrayString args = StringUtils::BuildArgv(cmd);
413 clDEBUG() << "Executing:" << cmd << endl;
414 clDEBUG() << "As array:" << args << endl;
415 return Execute(parent, args, flags, workingDirectory, cb);
416 }
417
418 void UnixProcessImpl::StartReaderThread()
419 {
420 // Launch the 'Reader' thread
421 m_thr = new ProcessReaderThread();
422 m_thr->SetProcess(this);
423 m_thr->SetNotifyWindow(m_parent);
424 m_thr->Start();
425 }
426
427 void UnixProcessImpl::Terminate()
428 {
429 wxKill(GetPid(), GetHardKill() ? wxSIGKILL : wxSIGTERM, NULL, wxKILL_CHILDREN);
430 int status(0);
431 // The real cleanup is done inside ::ChildTerminatedSingalHandler() signal handler (app.cpp)
432 waitpid(-1, &status, WNOHANG);
433 }
434
435 bool UnixProcessImpl::WriteToConsole(const wxString& buff)
436 {
437 wxString tmpbuf = buff;
438 tmpbuf.Trim().Trim(false);
439 tmpbuf << "\n";
440 int fd = GetWriteHandle();
441 wxMemoryBuffer mb;
442 wxCharBuffer cb = buff.mb_str(wxConvUTF8).data();
443 mb.AppendData(cb.data(), cb.length());
444 return do_write(GetWriteHandle(), mb);
445 }
446
447 void UnixProcessImpl::Detach()
448 {
449 if(m_thr) {
450 // Stop the reader thread
451 m_thr->Stop();
452 delete m_thr;
453 }
454 m_thr = NULL;
455 }
456
457 void UnixProcessImpl::Signal(wxSignal sig) { wxKill(GetPid(), sig, NULL, wxKILL_CHILDREN); }
458
459 #endif // #if defined(__WXMAC )||defined(__WXGTK__)