1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
use std::thread;

use crate::util::errno::{errno, set_errno};

fn get_temp_environemt() -> Option<&'static str> {
    #[cfg(target_family = "windows")]
    {
        const TEMP: &str = "TEMP";
        Some(TEMP)
    }
    #[cfg(target_family = "unix")]
    {
        const TMPDIR: &str = "TMPDIR";
        const XDG_RUNTIME_DIR: &str = "XDG_RUNTIME_DIR";
        if std::env::var(XDG_RUNTIME_DIR).is_ok() {
            Some(XDG_RUNTIME_DIR)
        } else if std::env::var(TMPDIR).is_ok() {
            Some(TMPDIR)
        } else {
            None
        }
    }
}

fn have_observatory_url(url: &str, file_suffix: &str) {
    let temp = get_temp_environemt();
    match temp {
        Some(temp) => {
            let dir = std::env::var(temp).unwrap();
            let separator = if dir.ends_with('/') { "" } else { "/" };
            let info = VMServiceInfoFile { uri: url.into() };
            let content = serde_json::to_string_pretty(&info).unwrap();
            let file_name = format!("vmservice.{}", file_suffix);

            println!(
                "nativeshell: Writing VM Service info file into ${{{}}}{}{}",
                temp, separator, file_name,
            );

            let file = format!("{}{}{}", dir, separator, file_name);
            std::fs::write(file, &content).unwrap();
        }
        None => {
            println!("nativeshell: Could not determine temporary folder environment variable.");
            println!("nativeshell: VM Service info file not written.");
        }
    }
}

#[derive(serde::Serialize, serde::Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct VMServiceInfoFile {
    uri: String,
}

fn dup(fd: libc::c_int) -> libc::c_int {
    unsafe { libc::dup(fd) }
}

fn dup2(src: libc::c_int, dst: libc::c_int) -> libc::c_int {
    loop {
        set_errno(0);
        let res = unsafe { libc::dup2(src, dst) };
        if res == -1 && errno() == libc::EINTR {
            continue;
        }
        return res;
    }
}

#[allow(unused)]
fn _register_observatory_listener(file_suffix: String) {
    const STDOUT_FILENO: i32 = 1;
    let stdout = dup(STDOUT_FILENO);
    let mut pipe = [0; 2];
    unsafe {
        #[cfg(target_family = "windows")]
        libc::pipe(pipe.as_mut_ptr(), STDOUT_FILENO as u32, libc::O_NOINHERIT);

        #[cfg(target_family = "unix")]
        libc::pipe(pipe.as_mut_ptr());

        libc::close(STDOUT_FILENO);
    }
    dup2(pipe[1], STDOUT_FILENO);
    thread::spawn(move || {
        let mut buf = [0u8; 1024];
        let mut string = String::new();
        let mut have_url = false;

        const URL_PREFIX: &str = "flutter: Observatory listening on ";
        loop {
            let read = unsafe {
                #[cfg(target_family = "windows")]
                let read = libc::read(pipe[0], buf.as_mut_ptr() as *mut _, buf.len() as u32);

                #[cfg(target_family = "unix")]
                let read = libc::read(pipe[0], buf.as_mut_ptr() as *mut _, buf.len());

                if read < 0 {
                    panic!("Could not read from stdout");
                }

                #[cfg(target_family = "windows")]
                libc::write(stdout, buf.as_ptr() as *const _, read as u32);

                #[cfg(target_family = "unix")]
                libc::write(stdout, buf.as_ptr() as *const _, read as usize);
                read
            };

            if have_url {
                continue;
            }

            let utf8 = String::from_utf8_lossy(&buf[0..read as usize]);
            string.push_str(&utf8);

            while let Some(i) = string.find('\n') {
                {
                    let substr = &string[..i];
                    if let Some(url) = substr.strip_prefix(URL_PREFIX) {
                        have_url = true;

                        // after reverting to the original stdout there's no flutter output
                        // anymore; Would be nice to know why this happens;
                        #[cfg(target_family = "windows")]
                        {
                            let file_suffix = file_suffix.clone();
                            let url: String = url.into();
                            thread::spawn(move || {
                                have_observatory_url(&url, &file_suffix);
                            });
                        }

                        #[cfg(target_family = "unix")]
                        {
                            // revert to the original stdout and terminate the thread
                            dup2(stdout, STDOUT_FILENO);
                            have_observatory_url(&url, &file_suffix);
                            return;
                        }
                    }
                }
                string.replace_range(..i + 1, "");
            }
        }
    });
}

#[allow(unused_variables)]
pub fn register_observatory_listener(file_suffix: String) {
    #[cfg(any(flutter_profile, debug_assertions))]
    {
        _register_observatory_listener(file_suffix);
    }
}